Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ "Virtual functions handling on multiple base classes"

I need to derive a child class CDerived from two different base classes CBaseA and CBaseB.

In addition, I need to call virtual functions of both parents on the derived class. Since I want to manage differently typed objects in one single vector later (this is not part of this minimal code expample), I need to call the virtual functions from a base class pointer to the derived class object:

#include <iostream>
#include <stdlib.h>

class CBaseA
{
  public:
    virtual void FuncA(){ std::cout << "CBaseA::FuncA()" << std::endl; };
};

class CBaseB
{
  public:
    virtual void FuncB(){ std::cout << "CBaseB::FuncB()" << std::endl; };
};

class CDerived : public CBaseB, public CBaseA
{};

int main( int argc, char* argv[] )
{
  // An object of the derived type:
  CDerived oDerived;

  // A base class pointer to the object, as it could later
  // be stored in a general vector:
  CBaseA* pAHandle = reinterpret_cast<CBaseA*>( &oDerived );

  // Calling method A:
  pAHandle->FuncA();

  return 0; 
}

Problem: But when running this on my computer, FuncB() is called instead of FuncA(). I get the right result, if I "flip" the parent class deklarations around, i.e.

class CDerived : public CBaseA, public CBaseB

but this doesn't solve my problem, since I cannot be sure which function will be called.

So my question is: What am I doing wrong and what is the correct way of handling such a problem?

(I am using g++ 4.6.2, by the way)

like image 588
user1628282 Avatar asked Jun 01 '26 04:06

user1628282


1 Answers

CBaseA* pAHandle = reinterpret_cast<CBaseA*>( &oDerived );

Do not use reinterpret_cast for performing a conversion to a base class. No cast is required; the conversion is implicit:

CBaseA* pAHandle = &oDerived;

For converting to a derived class, use static_cast if the object is known to be of the target type or dynamic_cast if it is not.

Your use of reinterpret_cast yields undefined behavior, hence the "odd" behavior that you see. There are few correct uses of reinterpret_cast and none of them involve conversions within a class hierarchy.

like image 94
James McNellis Avatar answered Jun 03 '26 21:06

James McNellis



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!