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)