inheritance - C++: Inheriting functions that return base class pointer -


i have base class base , class inherits called derived. class base has virtual function returnptrtoself() returns pointer itself. derived has original member function derivedfunc() base has not.

#include <iostream>  class base { public:     virtual base* returnptrtoself() {         return this;     } };  class derived : public base { public:     void derivedfunc() {         std::cout << "i derived" << std::endl;     } }  int main() {     derived d;     d.derivedfunc();                                   // works     d.returnptrtoself()->derivedfunc();                // error     ((derived*)d.returnptrtoself())->derivedfunc();    // works } 

the error not go away unless implement derived's own returnptrtoself() returns derived*.

i making lot of derived classes , think tedious implement original version of function each derived class. there more convenient way of fixing error other tedious way?

no, there isn't. if derivedfunc inherits base should support, should reflected in base:

struct base {     virtual void func() = 0; };  struct derived : base {     void func() override { std::cout << "i derived" << std::endl; } };  base* b = new derived; b->func(); 

if derivedfunc only applicable derived, wouldn't make sense able access base anyway. if base anotherderived instead? in cases need call derivedfunc, have functions take derived* (or derived&) instead of base* (or base&).

as last resort, if there's case absolutely need call derivedfunc on derived uniquely, there's always:

void maybecallderivedfunc(base* b) {     if (auto d = dynamic_cast<derived*>(b)) {         d->derivedfunc();     } } 

Comments