Ricardo_arg
Ricardo_arg

Reputation: 520

c++ using the child class methods of a class that inherits an interface

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

Answers (2)

TractorPulledPork
TractorPulledPork

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

dchhetri
dchhetri

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

Related Questions