I have a base class Base and a class that inherits it called Derived. Class Base has a virtual function returnPtrToSelf() that returns a pointer to itself. Derived has its original member function derivedFunc() which Base has not.
#include <iostream>
class Base {
public:
virtual Base* returnPtrToSelf() {
return this;
}
};
class Derived : public Base {
public:
void derivedFunc() {
std::cout << "i am derived" << std::endl;
}
}
int main() {
Derived d;
d.derivedFunc(); // works
d.returnPtrToSelf()->derivedFunc(); // ERROR
((Derived*)d.returnPtrToSelf())->derivedFunc(); // works
}
The error will not go away unless I implement Derived's own returnPtrToSelf() that returns a Derived*.
I am making a lot of derived classes and think it is tedious to implement an original version of this function for each derived class. Is there a more convenient way of fixing that error other than this tedious way?
static_cast<Derived*>(d.returnPtrToSelf())instead?Basedoesn't declare any function memberderivedFunc(), thus you can't access it via aBase*pointer.