Let's say that I have a parent class Parentand child classes Child1and Child2, in which the latter implements 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 I will say that I am assigned a pointer Parent*, and I want to check if the object implements MyInterface, and if so, add it to MyInterface*.
I tried to achieve this like this:
void MyFunction(Parent* p) {
MyInterface* i = dynamic_cast<MyInterface*>(p);
if (i != 0)
DoSomething();
else
cout << "Cannot do anything.";
}
But I am always 0, which says that it is never subject to type MyInterface*, even if I know for sure that the object is of good type.
How do I achieve this?
source
share