Demonstrate what are the other area where copy constructor is called using C++ programme.
A copy constructor is a member function that initializes an object using another object of the same class. A copy constructor has the following general function prototype:
#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 &p1) {x = p1.x; y = p1.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(5, 10);
Point p2 = p1;
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
Copy Constructor may be called in the following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed by value as an argument.
3. When an object is constructed based on another object of the same class.
Comments
Leave a comment