Example & Tutorial understanding programming in easy ways.

What is copy constructor in C++?

What is constructor?
Basically, constructor is the special type of function in class which can automatically called at the time of object creation.
or,
constructor is the function which will called when we create any new object.

Constructor property:
-Class name and constructor name should be same.
-There is no return type of constructor like void,int etc.

Type of constructor:
1.Default constructor
2.Parametrized constructor
3.Copy constructor

3.Copy constructor:
-A copy constructor is a member function which initializes an object using another object of the same class.

program:

#include< iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x1, int y1) {
x = x1;
y = y1;
}
// Copy constructor
Point(const Point &p2) {
x = p2.x;
y = p2.y;
}
int getX() {
return x;
}
int getY()
{
return y;
}
};
int main()
{
Point p1(10, 15);
// Normal constructor is called here
Point p2 = p1;
// Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); cout << "np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}


output-

p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15




Read More →
Search
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!