#include <iostream>
#include <cassert>
staticconstunsignedint defData(0xff);
class CBasedata
{
public:
CBasedata(unsignedint data=defData) : mydata(data) {};
virtual ~CBasedata(){};
protected:
unsignedint mydata;
};
class CBase : virtualpublic CBasedata
{
public:
CBase(unsignedint data=defData): CBasedata(data) {};
virtual ~CBase(){};
unsignedint data(){ return mydata; };
};
class CDerived : virtualpublic CBase
{
public:
CDerived(unsignedint data) : CBase(data) {};
virtual ~CDerived(){};
};
int main ( int argc, char** argv)
{
constunsignedint derivedValue(1);
CDerived myDerived(derivedValue);
std::cerr << "My original data is " << derivedValue << "\n";
std::cerr << "My derived data is " << myDerived.data() << "\n";
assert(derivedValue == myDerived.data());
};
which gives me the following output:
My original data is 1
My derived data is 255
CMinimalInheritance.exe: CMinimalInheritance.cpp:38: int main(int, char**): Assertion `derivedValue == myDerived.data()' failed.
The program works fine without the virtual qualifiers or when i call teh CBasedata constructor in CDerived constructor explicitly. So the CBase constructor doesn't seem to call the CBasedata constructor in the virtual case.
Does enybody know, if this is intended, or maybe a compiler bug?
virtual keyword is only to avoid dimond inheritance problem
Yes, when used like this. I thought the OP was aware of that and what he posted was just part of his code (the part where the problem was located). Anyway, in the same FAQ I gave him above he can also see what's the diamond problem and how he can use the virtual keyword to solve it.
"m4ster r0shi" is right in the assumption, that I posted only a part of the code. As is wrote, I have multiple inherited classes from CBase. It's like this:
1 2
class CNiceFeature : publicvirtual CDerived;
class CDerivedWithNiceFeature: publicvirtual CNiceFeature, publicvirtual CDerived
CNiceFeature is derived from CBase because it need access to CBaseData and CBase members and has additional parameters. Maybe there is a better way to do this. There are a lot of classes derived from CBase and CNiceFeature.
As the FAQ clarified (thanks again), I need to state all constructor manually on virtual derived classes. Otherwise the default constructor is called.
I guess my initial example was wrong in that way, that it mislead to a wrong assumption about the intended structure. Will do better next time.