Search code examples
c++g++copy-constructorconstructor-overloading

Can I separate the 2 types of syntax that call copy constructors into 2 different methods?


Since a copy constructor can be invoked by constructing with another object of the same type as the argument or by assignment, I was wondering if was possible to separate the two.

I tried making 2 variations (where the only difference was the line of code used to copy the object) and generating assembly for both, but the assembly output was exactly the same, which leads me to believe that it's not possible to differentiate them, unless it is just 'optimised out'.

Can I have 2 different copy constructors, one for Thing thing2(thing1) and one for Thing thing2 = thing1?

#include <iostream>
class Thing {
public:
    Thing() {
    }
    Thing(const Thing& from) {
        std::cout << "Copy constructor\n";
    }
};
int main()
{
    Thing thing1;
    Thing thing2(thing1); // This line is identical
    Thing thing3 = thing1; // to this one
    return 0;
}

Solution

  • Yes, in your particular example, you can distinguish between the 2 versions like this:

    class Thing {
    public:
        Thing() {
        }
        explicit Thing(Thing& from) {
            std::cout << "Constructor One\n";
        }
        Thing(Thing const&) {
            std::cout << "Constructor Two\n";
        }
    };
    

    and now the initializations will call different constructors:

    int main()
    {
        Thing thing1;
        Thing thing2(thing1);  // Constructor One  
        Thing thing3 = thing1; // Constructor Two
        return 0;
    }
    

    Here's a demo.

    Note that this only works for your example because thing1 is non-const. If it's const, then both initialization versions will call the 2nd constructor.