C ++ check at runtime if an object implements an interface

I asked this question a while ago: Multiple inheritance of inheritance from a base class to another derived class

But I'm still not sure I understand the answer. Question: 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 the way I want. But, as I understand it, according to the previous question, this should not. Therefore, I'm not sure if such code is valid. Thank!

+3
source share
5 answers

This is a valid code.

?
dynamic_cast , , , , .
, , Derived, Derived Interface ( Derived Interface) , , dynamic_cast .

+4

, ( ), dynamic_cast , .

static_cast, dynamic_cast . , NULL . , , .

, , , dynamic_cast .

+2

dynamic_cast , . .

0

:

Base *b = new B();
Interface *i = dynamic_cast<Interface *>( b );

? . , Base Interface . , Base , Interface, (: Interface) Base dynamic_cast.

0

, 5.2.7 4 ( ++ 2003):

:

- , () v, v () - T, - T -, () v, - ( lvalue) T.

- , v () - , T, , ( lvalue) - T .

- .

Note the use of the "most derived object" during the execution check. In your example, the "most derived object" for your object Base *bis an object Derived. Since the class Derivedis publicly inherited both from Baseand Interface, this object Base*can be carried over Interface*in this particular case.

0
source

All Articles