Home | | Computer Science 11th std | C++: Copy Constructors

Example Programs in C++ - C++: Copy Constructors | 11th Computer Science : Chapter 14 : Classes and objects

Chapter: 11th Computer Science : Chapter 14 : Classes and objects

C++: Copy Constructors

A constructor having a reference to an already existing object of its own class is called copy constructor.

Copy Constructors

 

A constructor having a reference to an already existing object of its own class is called copy constructor. In other words Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type. It is usually of the form simple (simple&), where simple is the class name. The compiler provides a default Copy Constructor to all the classes.

 

Calling copy constructors

 

A copy constructor is called

 

1) When an object is passed as a parameter to any of themember functions

Example void simple::putdata(simple x);

2) When a member function returns an object

Example simple getdata() { }

3) When an object is passed by reference to an instance of its own class

For example, simples1, s2(s1); // s2(s1) calls copy constructor

 

Illustration 14.26 to illustrate Copy constructor

#include <iostream>

using namespace std;

class Test

{

private:

int X;

int Y;

public:

      Test (int , int );         //parameterized constructor declaration

      Test (Test &); //Declaration of copy constructor to initialize data members.

void    Display();

};//End of class

Test:: Test(int a, int b)   //Definition of parameterized constructor.

{

      X = a;

      Y = b;

}

Test::Test(Test &T)      //Definition of copy constructor.

{

      X = T.X;

      Y = T.Y;

}

void Test:: Display()//Definition of Display () member function.

{

cout<<endl<< "X: " << X;

cout<<endl<< "Y: " << Y <<endl;

}

int main()

{

      Test T1(10,20) ; //Parameterized Constructor automatically called when

      //object is created.

      cout<<endl<<"T1 Object: " <<endl;

      cout<< "Value after initialization : " ;

      T1.Display();

      Test T2(T1);//Intialize object with other object using copy constructor cout<<endl<< "T2 Object: " <<endl;

      cout<< "Value after initialization : ";

      T2.Display();

      return 0;

}

Output:

T1 Object:

Value after initialization :

X: 10

Y: 20

T2 Object:

Value after initialization :

X: 10

Y: 20


Tags : Example Programs in C++ , 11th Computer Science : Chapter 14 : Classes and objects
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 14 : Classes and objects : C++: Copy Constructors | Example Programs in C++

Related Topics

11th Computer Science : Chapter 14 : Classes and objects


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.