×

C++ Copy Constructor


What are Copy Constructors ?

Copy Constructors , as a word says copy constructor of one object into another object of same type. Example, create object of one class . Create another object of same class and pass first object as a parameter to second object. Read carefully or see the example's main function to understand this statement.

#include <iostream>
using namespace std;
class Game
{
public:
  int abc;
   Game(int a)
   {
    abc = a;
    cout <<"Parameterised Constructor = " << a;

   }

  Game(Game &pacManObjectInstance)
  {
   cout <<"Copy Constructor is called and = "<<pacManObjectInstance.abc;
  }

}; 

int main()
{
 Game sankeObject(2);                 // Creatig Game class's object
 Game pacmanObject (sankeObject);     // Passing snakeObject to pacmanObject as a Copy Constructor.     
}

Output :-

Parameterised Constructor = 2
Copy Constructor is called and = 2