Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

something like virtual member(structure)

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)

like image 347
Meloun Avatar asked Dec 12 '25 14:12

Meloun


2 Answers

No, because you're creating two instances yourself. The base class has an instance, and the derived class has an instance (of a class extending the base class' inner class).

You can't modify the structure of the base class outside of it - once you defined it, it stays like that.

like image 166
Luchian Grigore Avatar answered Dec 14 '25 22:12

Luchian Grigore


Sort of, 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 another level of inheritance then B would derived virtually from stEntryDerived.

Now you have to refer to the fields as a.aa, b.cc, there is no member entry. Also, the stEntry types are no longer POD (so bb and cc may no longer be adjacent in memory). Finally, the size increase due to the virtual inheritance might actually be bigger than two ints.

What you can do, is get an stEntryDerived* or stEntryDerived& from an instance of B. Then that pointer/reference can be used to access aa, bb, and cc as the members of stEntryDerived, without the user needing to know about B. So you've achieved separation of interface, at some cost.

like image 32
Steve Jessop Avatar answered Dec 14 '25 22:12

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!