Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ checking at runtime if object implements interface

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!

like image 356
Andrew Avatar asked Feb 20 '23 15:02

Andrew


1 Answers

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.

like image 87
Alok Save Avatar answered Mar 05 '23 11:03

Alok Save