Constructor in C++
Constructor in C++
class MyClass
{
public:
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
1) Default Constructor
A default constructor doesn’t have any arguments (or parameters)
2) Parameterized Constructor
Constructors with parameters are known as Parameterized constructors.
These type of constructor allows us to pass arguments while object
creation.
Default constructor:
XYZ() {
} ....
XYZ obj;
....
Parameterized Constructor:
XYZ(int a, int b) {
} ...
XYZ obj(10, 20);
Default Constructor
#include <iostream>
using namespace std;
class Website
{
public:
//Default constructor
Website()
{
cout<<"Welcome to BeginnersBook"<<endl;
}
};
int main()
{
Website obj1;
Website obj2;
return 0;
}
Output:
Welcome to BeginnersBook
Welcome to BeginnersBook
#include <iostream>
using namespace std;
class Add
{ public:
//Parameterized constructor
Add(int num1, int num2)
{
cout<<(num1+num2)<<endl;
}
};
int main(void)
{
Add obj1(10, 20);
}
Output: 30
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);