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_cast
tells 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 Derived
and each object of the type Derived
is also of the type Interface
(Since Derived
inherits from Interface
) and hence the dynamic_cast
is valid and it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With