I don't understand why this works. pReallyABase is a downcasted shared_pointer< Derived > which points to a base class instance.
I understand why the compiler lets me call pReallyABase->onlyForDerived() since I defined it as a derived class pointer, but why don't I get a runtime error when I try to invoke a derived class function using that pointer?
class Base {
public:
virtual string whatAmI() {
return "I am a Base";
}
};
class Derived : public Base {
public:
virtual string whatAmI() {
return "I am a Derived";
}
string onlyForDerived() {
return "I can do Derived things";
}
};
int main(int argc, char *argv[]) {
shared_ptr<Base> pBase = shared_ptr<Base>(new Base);
shared_ptr<Derived> pReallyABase = static_pointer_cast<Derived>(pBase);
cout << pReallyABase->whatAmI() << endl;
cout << pReallyABase->onlyForDerived() << endl; //Why does this work?
return 0;
}
Results
I am a Base
I can do Derived things