[comp.lang.c++] Virtual base class question

pfaust@hplego.HP.COM (Paul Faust) (11/29/89)

Declaring a base class to be virtual does not always mean that objects that
multiply and indirectly inherit the base class will have only one instance
of the object.  For example, in the following program:

class A {
public:
	int a;
};

class B {
public:
	int b;
};

class C : public virtual A {
public:
	int c;
};

class D : public virtual A{
public:
	int D;
};

class E : public B, public C, public D {
public:
	int e;
};

main () {
	E eobject;
	eobject.e = 1;
}


The C code that is generated for the definitions of A, B, C, D, and E looks
as follows:

struct A {	/* sizeof A == 4 */

int a__1A ;
};

struct C {	/* sizeof C == 12 */

int c__1C ;
struct A *PA;
struct A OA;
};

struct D {	/* sizeof D == 12 */

int D__1D ;
struct A *PA;
struct A OA;
};

struct B {	/* sizeof B == 4 */

int b__1B ;
};



struct E {	/* sizeof E == 32 */

int b__1B ;
struct C OC;
struct D OD;

int e__1E ;
};

If one looks carefully, there are two instances of class A within E; one 
found in OC and one found in OD.  The PA's that are found in OC and OD 
will be pegged to the A found in OC, leaving the one in OD left not 
referenced.

If C or D were placed first in the inheritance list, only one copy of A 
would be found.  The items of C or D would have been generated individually 
and the output of A would have been omitted.  This behavior only works for 
the first class though.

My question is that in the definition of virtual base classes, does it 
imply only one occurrence of the inherited object is included in class 
that inherits it or does it mean solely that only one instance of the 
object is referenced in the inheriting class?  It appears that with the 
AT&T implementation, if a class inherits a virtual class either directly 
or indirectly, at best, only n - 2 copies would be found in the class 
(If E inherited class A virtually in this example, there would have been 
still 2 copies) and at worst case would there would be n copies.