Search⌘ K

Significance of Copy Constructor

Explore the importance of the copy constructor in C++ by understanding how and when it is called, including object initialization, passing objects to functions by value, and return by value. Learn about compiler optimizations that affect its invocation to better manage class objects in your programs.

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.

C++
// 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
...