Just make sure you tell the compiler about your derived class before first use:
class Child; // forward declaration class Base { public: Base * foo( void); }; class Child : public Base { }; // the function needs to be defined after the "Child" is known Base * Base::foo( void) { //some code return new Child; // will be automatically type-cast to base class } //————————————————————————————————————————————————— #include <iostream> #include <typeinfo> using namespace std; int main( void) { Base * base_p = Child().f(); cout << typeid( *base_p).name(); //expected to get "Child" return 0; }
However, I would recommend a different template:
class Child; // forward declaration class Base { public: static Base * foo( void); // static "factory" method }; class Child : public Base { }; // the function needs to be defined after the "Child" is known Base * Base::foo( void) { //some code return new Child; // will be automatically type-cast to base class } //————————————————————————————————————————————————— #include <iostream> #include <typeinfo> using namespace std; int main( void) { Base * base_p = Base::f(); // use scope resolution, not object method cout << typeid( *base_p).name(); //expected to get "Child" return 0; }
source share