Copy Constructor

  • To create a copy of an existing object of class.
  • By default class provides copy constructor.

Let's understand with example:

CODE:

#include<iostream>
Using namespace std;
Class Points
{
Private:
    Int x, y;
Public:
    Points(int x1, int y1) { x = x1; y = y1; }
    Points(const Point &p2) {x = p2.x; y = p2.y; }
    Int getX()            {  return x; }
    Int getY()            {  return y; }
};
Int main()
{
    Points p1(4, 11);
    Points p2 = p1;
    Points p3 = p2;
    Points p4 = p3;
    Cout << “Use the copy constructor in class code and print the value of an object four times.\n\n\n”;
    Cout << “p1.x = “ << p1.getX() << “, p1.y = “ << p1.getY();
    Cout << “\np2.x = “ << p2.getX() << “, p2.y = “ << p2.getY();
    Cout << “\np3.x = “ << p3.getX() << “, p3.y = “ << p3.getY();
    Cout << “\np4.x = “ << p4.getX() << “, p4.y = “ << p4.getY();
    Return 0;
}

OUTPUT:

0 Comments