i want to use multiple inheritance. but i get the following compiler error:
error C2512: 'Object::Object' : Kein geeigneter Standardkonstruktor verfuegbar
error C2512: 'Object::Object' : No suitable StandardConstructor available
When using virtual inheritance the same instance of Object is shared by both Object1 and Object2 when they are part of an instance of Object4. This means that if both Object1 and Object2 were allowed to initialise Object, the constructor would be run twice, which would not be correct.
The rule in C++ is, the initialisers for Object in Object1 and Object2s' constructors are ignored. (That is, they do not run) The virtual base must be initialised directly from Object4.
class Object
{
public:
Object(int c)
{
printf("Object\n");
a = 0;
}
~Object()
{
printf("~Object\n");
}
int a;
};
class Object1 : publicvirtual Object
{
public:
// Call to Objects constructor is not called when instance is part of an Object4
Object1(int c) : Object(c)
{
printf("Object1\n");
a1 = 0;
a = 1;
}
~Object1()
{
printf("~Object1\n");
}
int a1;
};
class Object2 : publicvirtual Object
{
public:
// Call to Objects constructor is not called when instance is part of an Object4
Object2(int c) : Object(c)
{
printf("Object2\n");
a2= 0;
a = 2;
}
~Object2(){
printf("~Object2\n");
}
int a2;
};
class Object4 : publicvirtual Object1, publicvirtual Object2
{
public:
// Note extra call to Object's constructor
Object4(int c) : Object1(c), Object2(c), Object(c)
{
printf("Object4\n");
a4 = 0;
a = 4;
}
~Object4()
{
printf("~Object4\n");
}
int a4;
};
IIRC:
You don't need the base classes Object1 and Object2 of Object4 to use virtual inheritance, and the initializer for Object should be first in the Object4 constructor's init list.
ropex: The order of the initialisation list has no impact on the order of initialisation. Object will always be initialised first.
And yes, your right, in this case the virtual keywords on line 57 could be removed.
The keyword virtual basically says "only put one instance of this base in derived classes if possible" so on line 57 you are currently saying the classes derived from Object4 should treat Object1 and Object2 as virtual bases too.