I was recently asked this question in an interview:
#include <iostream> class Base { public: void foo() { std::cout << "foo" << std::endl; } }; class Derived : public Base { public: void bar() { std::cout << "bar" << std::endl; } }; int main(int argc, const char *argv[]) { Base *p = new Derived; // additional code here return 0; } The conditions on the question were that the Base and Derived classes cannot be changed (for example changing the name of the methods, adding additional methods, or changing a method to virtual. A further restriction was that no type of cast could be used. The pointer p had to be used. Other than that, you could write any additional code, including as many classes as necessary to insure that the "bar()" method was called using the object pointed to by p.
Given that no casts were allowed, the only aswer I could come up with was an old-school one:
Derived *d; memcpy(&d, &p, sizeof p); d->bar(); Which is even worse than a cast. The interviewer berated me and told me I didn't have even the most basic knowledge of object hierarchy since I could not see the very obvious, trivial solution to the question.
I apologize if this question is a duplicate; I've seen other questions about accessing a method in a derived class from a base class, but in all cases I saw, the answer involved either a cast or modification to either of the classes.
He may be correct; I've been programming in C++ for over 15 years and I cannot see the solution. It could be I've never encountered it since I would use a cast in this situation: in this case, it would have to be a static_cast since there are no virtual methods (not even the destructor) which would allow the dynamic_vast to compile (it fails with a message: "'Base' is not a polymorphic type"