I have class A with basic members and functions:
class A{
public:
typedef struct{
int aa;
int bb;
} stEntry;
stEntry entry;
void function1();
void function2();
};
Than class B that should extend class A including structure stEntry…
class B : public A{
public:
typedef struct :stEntry
{
int cc;
} stEntry;
stEntry entry;
void function3();
};
and then:
int main() {
A a;
B b;
a.entry.aa = 1;
b.entry.aa = 2;
b.entry.cc = 3;
cout << "class A:"<<sizeof(a)<< endl;
cout << "class B:"<<sizeof(b)<< endl;
return 0;
}
I get
class A:8
class B:20
So class B contains 2 instances – 8 bytes(A class member) + 12 bytes(B class member).
Is there a way how to extend structure stEntry for class B? (without have 2 instances)
Sort of, with virtual inheritance:
If you want to go another level of inheritance then
Bwould derived virtually fromstEntryDerived.Now you have to refer to the fields as
a.aa,b.cc, there is no memberentry. Also, thestEntrytypes are no longer POD (sobbandccmay no longer be adjacent in memory). Finally, the size increase due to the virtual inheritance might actually be bigger than twoints.What you can do, is get an
stEntryDerived*orstEntryDerived&from an instance ofB. Then that pointer/reference can be used to accessaa,bb, andccas the members ofstEntryDerived, without the user needing to know aboutB. So you’ve achieved separation of interface, at some cost.