DorHugi
DorHugi

Reputation: 152

Are members in a c++ class guaranteed be contiguous?

Are class members in c++ guaranteed to be contiguous?

I've tried running the following code with almost all popular c++ compilers, and all of them yield the result 4, which is the relative address of the variable y. Is that a coincidence, or is it guaranteed by the language specifications to be this way? Isn't it possible that the compiler will not make the members x and y contiguous with the class basic address/ contiguous with each other?

Please note that this thread does not answer this question.

#include <iostream>

using namespace std;

class A {
public:

    void f(){
        cout << &(this->y) << endl;
    }

    int x, y;
};


int main(int argc, const char* argv[])
{
    A *a = 0;
    a->f();

    return 0;
}

Upvotes: 3

Views: 1773

Answers (1)

Bathsheba
Bathsheba

Reputation: 234695

Because your class is not a polymorphic type, has no base class, and all the members are public, the address of x is guaranteed to be the address of the class.

Also, the address of y is guaranteed to be after the address of x, although there could be an arbitrary amount of padding between them. So yes, your result is a coincidence.

If your class is polymorphic, i.e. has a virtual function somewhere in either it or a base class, or the members are protected or private, then all bets are off.

So in your case, (void*)&(this->x) is (void*)this, and the address of this->y must be higher than the address of this->x.

Finally if you need the class members to be contiguous, and mutually reachable by pointer arithmetic, use

int x[2];

instead as the member.

Upvotes: 6

Related Questions