Advertisement
YouKnowWho07

Constructor

Jun 9th, 2023
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. /// Code-01
  2. /// Default constructor example:
  3. #include<iostream>
  4. using namespace std;
  5.  
  6. class Name{
  7. public:
  8.  
  9.     Name() // default constructor
  10.     {
  11.         cout<< "This is my name"<<endl;
  12.     }
  13. };
  14.  
  15. int main()
  16. {
  17.     Name obj, abc, xyz;
  18. }
  19.  
  20. /// Code - 02
  21. /// Constructor with parameter
  22. #include <iostream>
  23. using namespace std;
  24.  
  25. class Car {      
  26.   public:          
  27.     string brand;  
  28.     string model;  
  29.     int year;    
  30.     Car(string x, string y, int z) {  // Constructor with parameters
  31.       brand = x;
  32.       model = y;
  33.       year = z;
  34.     }
  35. };
  36.  
  37. int main() {
  38.   // Create Car objects and call the constructor with different values
  39.   Car carObj1("BMW", "X5", 1999);
  40.   Car carObj2("Ford", "Mustang", 1969);
  41.  
  42.   // Print values
  43.   cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  44.   cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  45.   return 0;
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement