...

/

Significance of Copy Constructor

Significance of Copy Constructor

Understand the purpose and significance of copy constructors.

We'll cover the following...

Problem

What purpose does a copy constructor serve and how is it different from a normal constructor?

Coding solution

Here is a solution to the problem above.

Press + to interact
// Program to demonstrate cases when copy constructor is called
#include <iostream>
class Circle
{
private :
int radius ;
float x, y ;
public :
Circle( )
{
radius = x = y = 0 ;
}
Circle ( int rr, float xx, float yy )
{
radius = rr ;
x = xx ;
y = yy ;
}
Circle ( const 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 ;
}
void setData ( Circle c )
{
radius = c.radius ;
x = c.x ;
y = c.y ;
}
} ;
Circle fun( )
{
Circle c ;
return c ;
}
int main( )
{
Circle c1 ( 10, 2.5, 3.5 ) ;
Circle c2 = c1 ;
c2.showData( ) ;
Circle c3 ;
c3.setData ( c1 ) ;
c3.showData( ) ;
Circle c4 = fun( ) ;
c4.showData( ) ;
return 0 ;
}

Explanation

A copy constructor gets invoked in three situations. These are as follows:

  1. When instantiating one object and initializing it
...