0 votes
in C Plus Plus by

What is a COPY CONSTRUCTOR and when is it called?

1 Answer

0 votes
by
A copy constructor is a constructor that accepts an object of the same class as its parameter and copies its data members to the object on the left part of the assignment. It is useful when we need to construct a new object of the same class.

Example:

class A{

             int x; int y;

             public int color;

             public A() : x(0) , y(0) {} //default (no argument) constructor

             public A( const A& ) ;

};

A::A( const A & p )

{

              this->x = p.x;

              this->y = p.y;

              this->color = p.color;

}

main()

{

            A Myobj;

            Myobj.color = 345;

            A Anotherobj = A( Myobj ); // now Anotherobj has color = 345

}

Related questions

+1 vote
0 votes
asked Jun 1, 2022 in JAVA by SakshiSharma
+1 vote
asked Mar 2, 2020 in ReactJS by RShastri
...