There is some virtual method in base class that return same base object (not pointer). In some of virtual overrides I want to return derived object as base. But problem is that method always creates base object from returning derived. Here is simple example:
#include <iostream>
#include <string>
class Base {
public:
Base() {}
virtual std::string myName() { return "Base"; }
virtual Base createAlike() { return Base(); }
};
class Derived : public Base {
public:
Derived() : Base() {}
std::string myName() override { return "Derived"; }
Base createAlike() override { return Derived(); }
};
int main() {
Derived d;
Base d1 = d.createAlike();
std::cout << d.myName() << std::endl;
std::cout << d1.myName();
return 0;
}
that outputs:
Derived
Base
How to correct it?