5

Say that i have some classes like this example.

class A {
     int k, m;
public:
     A(int a, int b) {
          k = a;
          m = b;
     }
};

class B {
     int k, m;
public:
     B() {
          k = 2;
          m = 3;
     }
};

class C : private A, private B {
     int k, m;
public:
     C(int a, int b) : A(a, b) {
          k = b;
          m = a;
     }
};

Now, in a class C object, are the variables stored in a specific way? I know what happens in a POD object, but this is not a POD object...

2 Answers 2

2

In the introduction of Chapter 10, Derived classes, the C++ Standard mentions:

The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified.

So, in your example C objects each have a base class subobject of type A and a base class subobject of type B, but whether the A base member comes before or after the B base member is unspecified.

Sign up to request clarification or add additional context in comments.

Comments

0

Although I'm not sure if it's required by the standard, in any reasonable implementation I'm aware of they are stored in this order: A::k, A::m, B::k, B::m, C::k, C::m (possibly aligned according to the hardware's requirements). The only practical reason in this knowledge I can think of is that you need to understand that if you cast a pointer to C to a pointer to B, then its value (the address) will be different, so you should be very careful about such casts (don't use reinterpret_cast<> for this, for example).

2 Comments

This is probably true for many implemenations, but I don't think there's any guarantee.
@jdv, true, it is probably implementation-specific, but I can't think of any other way it could be implemented. Should add a note to the answer, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.