I know of the following situations in c++ where the copy constructor would be invoked:
when an existing object is assigned an object of it own class
I might be wrong about this, but this class allows you to see what is called and when:
class a {
public:
a() {
printf("constructor called\n");
};
a(const a& other) {
printf("copy constructor called\n");
};
a& operator=(const a& other) {
printf("copy assignment operator called\n");
return *this;
};
};
So then this code:
a b; //constructor
a c; //constructor
b = c; //copy assignment
c = a(b); //copy constructor, then copy assignment
produces this as the result:
constructor called
constructor called
copy assignment operator called
copy constructor called
copy assignment operator called
Another interesting thing, say you have the following code:
a* b = new a(); //constructor called
a* c; //nothing is called
c = b; //still nothing is called
c = new a(*b); //copy constructor is called
This occurs because when you when you assign a pointer, that does nothing to the actual object.