When will the copy constructure get called?

The copy constructor is called whenever a new instance of a class is created from another instance of the same class. This happens in the following cases:
  • An instance is declared which is initialized from another instance.

Person p("John"); //constructor is called

Person q = p; //copy constructor is called

Person r(p); //copy constructor is called

Person M; M = p;//assignment operator is called

  • When an instance value (neither reference nor point) is passed as argument

void foo(Person p) {......} //copy constructor is called, BAD PERFORMANCE

  • When an instance is returned from a function

Person foo(){Person m; return m;} //copy constructor is called, BAD PERFORMANCE

If there is not a copy constructor explicitly defined in the class, C++ compiler will generate a default copy constructor which copies (NOTE: here is the shallow copy) each member data.

Don't write default copy constructor when the shallow copy is OK. If the object has no pointers to dynamically allocated memory, the shallow copy is sufficient. Therefor the default copy constructor, default assignment operator and default destructor are OK and you don't need to write your own.

No comments:

Post a Comment