Interview Questions

What is a COPY CONSTRUCTOR and when is it called?

C++ Interview Questions and Answers


(Continued from previous question...)

What is a COPY CONSTRUCTOR and when is it called?

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

(Continued on next question...)

Other Interview Questions