I am trying to get the derived type of an object via a base class virtual function. I have written this, which does not compile:
struct base {
virtual base& get_this() {
return *this;
}
};
struct derived : base {
virtual derived& get_this() override {
return *this;
}
void fn();
};
int main () {
base* pd = new derived();
derived& x = pd->get_this(); /*ERROR*/
x.fn();
return 0;
}
... giving me an error that: I cannot initialize a derived&
from a base
. Since get_this
is virtual, why does pd->get_this()
return a base&
instead of a derived&
? Thanks in advance!
EDIT:
Thanks everyone for their useful answers and apologies for my late reply. I should have specified in the original post that I am also interested in a solution to my problem rather than just figuring out why the above does not compile. My main problem is that fn
is unique to the derived
class and cannot be called via the base class. Using casts sure solves the problem but I hate writing code with if else constructs just to get the right type (also Scott Meyers advise against casts :)) . The answers seem to indicate that casts are the way to go, which in a way is at least reassuring that I am not neglecting a more 'elegant' solution to my problem. Thanks again!
dynamic_cast
which will be a viable solution for the use case described. No one else mentioned this in the answers, and the way covariance is supported in C++ doesn't solve the OP's primary problem. – Talipes