Search code examples
c++virtualmovefactory

Does polymorphism apply on values? Or using move constructor of derived class when returning by (base-)value


I am building some kind of factory method which returns a DerivedClass as a BaseClass in the following way:

BaseClass Factory() 
{
    return DerivedClass();
}

Am I right, that the move constructor of the BaseClass is used when I call that method:

BaseClass object = Factory();

Since I cannot make the move constructor of the BaseClass virtual, is there an other way to force the move constructor of the DerivedClass to be taken?

Edit1: additional information - I already thought about pointers. But the thing is, I want to export the factory function in a DLL and I wanted to make it as easy as possible for the user. Standard pointers could result in memory leaks and on the other hand not everybody is familiar with smart pointers.

Edit2: As I learnd the real question was: Does polymorphism also work with return by value?
And the answer is NO.


Solution

  • I think you souldn't do:

    BaseClass Factory() 
    

    But rather

    // You'll need to delete
    BaseClass* Factory() {
        return new Derived();
    }
    
    // You will not need to delete
    unique_ptr<BaseClass> Factory() {
        // return new Derived();
        // As the comments point out: prefer use of make_unique
        return std::make_unique<Derived>();
    }
    

    Otherwise, you're slicing your object.

    Polymorphism works only in pointers and references.