Sierramike Sierramike - 2 months ago 6
C++ Question

How to cast from parent to interface of chlid class

Say I have a parent class

Parent
and child classes
Child1
and
Child2
having the latter implementing
MyInterface
:

class Parent {
public:
Parent();
virtual ~Parent();
virtual void MyMethod();
}
class MyInterface {
public:
virtual ~MyInterface() {}
virtual void MyInterfaceMethod() = 0;
}
class Child1 : public Parent {
public:
Child1();
virtual ~Child1();
}
class Child2 : public Parent, MyInterface {
public:
Child2();
virtual ~Child2();
virtual void MyInterfaceMethod() override;
}


And say I'm given a
Parent*
pointer, and I want to check if the object is implementing
MyInterface
and if yes, cast it to
MyInterface*
.

I've tried to achieve it this way:

void MyFunction(Parent* p) {
MyInterface* i = dynamic_cast<MyInterface*>(p);
if (i != 0)
DoSomething();
else
cout << "Cannot do anything.";
}


But i always equals to 0 which says it is never casted to the type
MyInterface*
even if I know for sure that the object has the good type.

How should I achieve this?

Answer

Child2 private inherits from MyInterface, unless MyFunction() has the privilege to access the private base subobject, dynamic_cast will always fail.

Since MyInterface seems to be an interface, I think you want public inheritance.

class Child2 : public Parent, public MyInterface { }
//                            ~~~~~~      

LIVE (Other errors fixed)