Search code examples
c++copy-constructordefault-constructor

Which one -- default or copy constructor -- of a class gets called when I define a function that has (non-reference) return type of that class?


I was puzzled as why I had to write copy constructor of this one class when I defined a function inside another class with the return type of the first mentioned class.

For example:

class Foo{
    // attributes
public:
    Foo(){...}

    // I had to write the CC
    Foo(const Foo& obj){
        //...
    }
}

class Bar{
// ....

// This is the function
Foo SomeFunction()
{
    Foo myVar;

    // ....

    return myVar;
}

I checked by couting that the copy constructor is actually being called.

I need confirmation though because it would seem more logical to me that the default constructor is called in this situation, like in this line where myVar is created.

I'm a beginner so I'm trying to wrap my head around these calls.


Solution

  • The line

    Foo myFunc;
    

    calls the default constructor.

    The line

    return myFunc;
    

    calls the copy constructor since the return type of the function is Foo. The object returned from the function is not myFunc but a copy of myFunc. myFunc gets deleted when the function returns. The copy is what the calling function gets.

    If the compiler is able to use RVO (return value optimization), then myFunc is returned to the calling function, not a copy. In that case, the copy constructor will not get called.