Copy Constructor

Learn how to define a copy constructor.

We'll cover the following...

Problem

How to define a copy constructor?

Coding solution

Here is a solution to the problem above.

Press + to interact
// Program to demonstrate use of copy constructor
#include <iostream>
class Circle
{
private :
int radius ;
float x, y ;
public :
Circle( )
{
}
Circle ( int rr, float xx, float yy )
{
radius = rr ;
x = xx ;
y = yy ;
}
Circle ( Circle& c )
{
std::cout << "Copy constructor invoked" << std::endl ;
radius = c.radius ;
x = c.x ;
y = c.y ;
}
void showData( )
{
std::cout << "Radius = " << radius << std::endl ;
std::cout << "X-Coordinate = " << x << std::endl ;
std::cout << "Y-Coordinate = " << y << std::endl ;
}
} ;
int main( )
{
Circle c1 ( 10, 2.5, 3.5 ) ;
Circle c2 = c1 ;
Circle c3 ( c1 ) ;
c1.showData( ) ;
c2.showData( ) ;
c3.showData( ) ;
return 0 ;
}

Explanation

Here object c1 is constructed through the three-argument constructor. Objects c2 and c3 are ...