Consider an object is created. The created object is initialized by using another object of same class. The object used for initializing the first object generates a constructor called as "copy constructor".
Copy constructors are used when pointer variables are declared in a class to maintain a copy to the original object of the same type.
Syntax
class_name (const class_name &obj)
{
//constructor body
}
Example
[c]
#include <iostream>
using namespace std;
class Triangle
{
public:
int getBase( void );
Triangle( int bas ); //constructor
Triangle( const Triangle &obj); // copy constructor
~Triangle(); // destructor
private:
int *ptr;
};
Triangle::Triangle(int bas)
{
cout << "simple constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = bas;
}[/c]
Output
[c]
simple constructor allocating ptr
Copy constructor allocating pointer.
The base of Triangle: 20
memory is cleaned up!
memory is cleaned up![/c]