I’v asked these question some time ago:
Multiple inheritance casting from base class to different derived class
But I’m still not sure I understand the answer. The question is: Is the code below valid?
#include <iostream>
using namespace std;
struct Base
{
virtual void printName()
{
cout << "Base" << endl;
}
};
struct Interface
{
virtual void foo()
{
cout << "Foo function" << endl;
}
};
struct Derived : public Base, public Interface
{
virtual void printName()
{
cout << "Derived" << endl;
}
};
int main(int argc, const char * argv[])
{
Base *b = new Derived();
Interface *i = dynamic_cast<Interface*>(b);
i->foo();
return 0;
}
The code works as I want. But as I understand, according to previous question, it should not. So I’m not sure if such code is valid. Thanks!
It is valid code.
Why?
Because
dynamic_casttells you if the object being pointed to is actually of the type you are casting to.In this case the actual object being pointed to is of the type
Derivedand each object of the typeDerivedis also of the typeInterface(SinceDerivedinherits fromInterface) and hence thedynamic_castis valid and it works.