Sobes.tech
Junior — Middle

In what cases does C++ automatically invoke the copy constructor?

sobes.tech AI

Answer from AI

Automatic invocation of the copy constructor in C++ occurs in the following cases:

  • When initializing an object with another object of the same type, for example:

    MyClass a;
    MyClass b = a; // copy constructor is called
    
  • When passing an object by value to a function:

    void func(MyClass obj); // calling func(a) will invoke the copy constructor
    
  • When returning an object by value from a function (before compiler optimizations):

    MyClass func() {
        MyClass a;
        return a; // may invoke the copy constructor
    }
    
  • When initializing an object in the initialization list of another object.

If the copy constructor is not explicitly defined, the compiler will generate it automatically if possible.