Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to one class and calling function from sibling class?

Tags:

c++

casting

I'm getting a pointer to a base class (which is actually a pointer to some derived class). Then I want to call a function on that derived class, but I don't know which one it is.

class Base
{

};

class DerivedOne : public Base
{
    public:
        void functionA()
        {   int x = 0;  }
};

class DerivedTwo : public Base
{
    public:
        void functionA()
        {   int x = 0;  }
};

int main()
{   
    Base* derivedTwoPtr = new DerivedTwo();

    reinterpret_cast<DerivedOne*>(derivedTwoPtr)->functionA(); 

    return 0;
}

This works as I want, but I have to say it looks rather dodgy. Is it defined behavior? If not, is there a legal way to dynamically resolve this?

like image 421
drby Avatar asked Jun 21 '26 02:06

drby


2 Answers

Hey, don't do that. That's what virtual methods are for.

class Base
{
public:
    virtual void functionA()=0;

};

class DerivedOne : public Base
{
    public:
        virtual void functionA()
        {       int x = 0;      }
};

class DerivedTwo : public Base
{
    public:
        virtual void functionA()
        {       int x = 0;      }
};

int main()
{   
    Base* derivedTwoPtr = new DerivedTwo();

    derivedTwoPtr->functionA(); 

    return 0;
}
like image 154
vava Avatar answered Jun 23 '26 19:06

vava


Just use virtual functions. That's what they are intended for. Your base class should look like

class Base
{
    virtual void functionA() = 0;
};

where the = 0 bit is optional. If present the virtual function is known as a pure virtual function and enforces each subclass of Base to implement the function.

Now if you call functionA through a Base pointer you will get the method appropriate to whichever subclass the pointer really points to.

like image 22
Troubadour Avatar answered Jun 23 '26 18:06

Troubadour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!