Reputation: 520
I am trying to use a method from a child that class that inherits from a interface. The call to that method done from a client class (main method). //interface method
class InterfaceMethod{
virtual void method(void) = 0;
}
This is the class that is inheritance the interface:
class ChildClass: public InterfaceMethod
{
public:
ChildClass(){}
~ ChildClass(){}
//virtual method implementation
void method(void)
{
//do stuff
}
//and this is the method that i want to use!
//a method declared in the child class
void anotherMethod()
{
//Do another stuff
}
private:
}
This is the client:
int main()
{
InterfaceMethod * aClient= new ChildClass;
//tryng to access the child method
(ChildClass)(*aClient).anotherMethod();//This is nor allowed by the compiler!!!
}
Upvotes: 0
Views: 111
Reputation: 793
Try it like this:
static_cast<ChildClass*>(aClient)->anotherMethod();
You shouldn't do this unless you can be sure that you have an instance of the derived class.
Upvotes: 0
Reputation: 7136
You want dynamic cast.
ChildClass * child = dynamic_cast<ChildClass*>(aClient);
if(child){ //cast sucess
child->anotherMethod();
}else{
//cast failed, wrong type
}
Upvotes: 4