Something like a virtual participant (structure)

I have a class A with basic elements and functions:

class A{
public:
    typedef struct{
        int aa;
        int bb;
    } stEntry;
    stEntry entry;

    void function1();
    void function2();
};

      

Than class B, which is supposed to extend class A, including the stEntry structure ...

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 (class member) + 12 bytes (class member B).

Is there a way to extend the stEntry structure for class B? (no two copies)

+3


source to share


2 answers


Sort, with virtual inheritance:

struct stEntryBase {
    int aa;
    int bb;
};

struct A : virtual stEntryBase {
    typedef stEntryBase stEntry;

    void function1();
    void function2();
};

struct stEntryDerived : virtual stEntryBase {
    int cc;
};

struct B : A, stEntryDerived {
    typedef stEntryDerived stEntry;

    void function3();
};

      

If you want to go to another level of inheritance, it B

will be obtained practically from stEntryDerived

.



Now you need to apply to fields like a.aa

, b.cc

no member entry

. Also, types are stEntry

no longer PODs ( bb

and therefore cc

can no longer be contiguous in memory). Finally, the increase in size due to virtual inheritance can actually be larger than two int

s.

What you can do is get stEntryDerived*

or stEntryDerived&

from an instance B

. This pointer / link can then be used to access aa

, bb

and cc

as members stEntryDerived

, without the user needing to know about B

. This way you have achieved a split interface for a small fee.

+2


source


No, because you are creating two instances yourself . A base class has an instance, and a derived class has an instance (a class that extends the inner class of the base class).



You cannot change the structure of the base class outside of it - once you define it, it stays that way.

+4


source







All Articles