What is a COPY CONSTRUCTOR and when is it called?

Posted Answers

A copy constructor is a method that accepts an object of the same class and copies it’s data members to the object on the left part of assignement:
class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
public Point2D( const Point2D & ) ;
};
Point2D::Point2D( const Point2D & p )
{
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}
main(){
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color = 345


Answer by: Anonymous
 
 

CC is one tht make one object intialised with other at the time of intialisation. value of object is passed by reference to the ctor. there r 2 ways to call cc ,
a a1=a2;//calling cc -1
a a1(a2);//calling cc -2
a1=a2; //just an assingment operation -3
statement 2& 3 r nt same as the 3 one is an assignment op while 2 is calling cc.
syntax of ccc in class is:
class name(classname &)
{//statement
}
a( a &a1)
{ x=a1.x;
y=a1.y;
}


Answer by: chunilal kukreja