Copy constructor is often quite confusing even for the geeks. Consider a situation of scores of many participants in a game to be initialized to same values but to be kept at different locations. In this case the moment we initialize score of one participant we would like that other participants are simply created based on first participants initial score but later they are separately tracked. The concept of copy constructor comes handy in such cases where we can decide what initialization routine will be called for first initialization and what for subsequent initialization.
Let us take this in form a code example –
class Player
{
int score;
public:
Player() { score = 0; }
Player(const Player& P) { score=P.score; }
};
int main()
{
Player P1;
Player P2=P1;
}
Let us understand the statements in main. Player P1 will simply declare an object where the default constructor without any arguments will be called.
The second statement is unique as Player P2=p1; where P2 has to be formed on the basis of initial values of P1. In this case it is needed that the copy constructor version Player(const Player& P) is called. This will make sure that data items are neatly copied and exact same initialisation is possible.
The copy constructor calling can be done using any one of the following syntax forms.
Player P2=P1 ; //Assignment Syntax Form
Player P2(P1); //Function Call Syntax Form
In general a user may not be required to explicitly write a copy constructor as it is automatically generated by compiler when such kind of object declaration is there. In certain cases the compiler generated copy constructor may not be good enough for e.g. in the case of File Pointers Referencing or Networking Related References etc. In such cases explicit copy constructor is useful to create distinct memory locations.