A constructor is a member function which has the same name as that of the class and does not have a return type. A constructor is called automatically when an object of the class is created.
The following program shows a constructor of the class ‘rectangle‘. The constructor is called automatically when an object of the class ‘obj1‘ is created.
#include<iostream>
using namespace std;
class rectangle {
public:
int length = 4;
int breadth = 7;
rectangle() {
cout<<"The length of the rectangle is "<<length<<endl;
cout<<"The breadth of the rectangle is "<<breadth;
}
};
int main () {
rectangle obj1;
return 0;
}
Output:
The length of the rectangle is 4
The breadth of the rectangle is 7
A constructor can also have parameters. The following program shows a constructor with parameters ‘x‘ and ‘y‘. An object ‘obj1‘ of the class is created and arguments are passed to print the output.
#include<iostream>
using namespace std;
class rectangle {
public:
int length;
int breadth;
rectangle (int x, int y) {
length = x;
breadth = y;
cout<<"The length of the rectangle is "<<x<<endl;
cout<<"The breadth of the rectangle is "<<y;
}
};
int main () {
rectangle obj1(4 , 7);
return 0;
}
Output:
The length of the rectangle is 4
The breadth of the rectangle is 7
A copy constructor is a member function which is used to copy contents of an object of a class. An another object is initialized with an object of the same class.
The following program shows a constructor and a copy constructor in class ‘rectangle‘. An object ‘obj2‘ copies the content of ‘obj1‘. A syntax of a copy constructor is ClassName (ClassName &ObjectName).
#include<iostream>
using namespace std;
class rectangle {
public:
int length;
int breadth;
rectangle (int x, int y) {
length = x;
breadth = y;
}
rectangle(rectangle &obj) {
length = obj.length;
breadth = obj.breadth;
}
};
int main () {
rectangle obj1(4 , 7);
cout<<"The length of the rectangle is "<<obj1.length<<endl;
cout<<"The breadth of the rectangle is "<<obj1.breadth<<endl;
rectangle obj2 = obj1;
cout<<"The length of the rectangle is "<<obj2.length<<endl;
cout<<"The breadth of the rectangle is "<<obj2.breadth;
return 0;
}
Output:
The length of the rectangle is 4
The breadth of the rectangle is 7
The length of the rectangle is 4
The breadth of the rectangle is 7