Yousf
Yousf

Reputation: 3997

Safety of pointer arithmatic on inherited objects

If we have the following code:

struct Base
{
    int x;
    int y;
    void foo();
    virtual unsigned getCrc() = 0;
};

struct Derived1 : public Base
{
    int a;
    int b;
    unsigned getCrc();
};

struct Derived2 : public Base
{
    float a;
    float b;
    unsigned getCrc();
};

Is it C++ standard that a and b should be after x and y in memory? Or it is the most used method for laying out inherited objected? (i.e. compiler defacto-standard).

In other words, can I guarantee that:

Derived1 obj;

    int* unsafe_internal_a = (int*)((unsigned)(&obj) + sizeof(Base));

EDIT: My question is 'Is memory layout covered in some standard? Or it is compiler dependent?'. The code is just for illustration.

Upvotes: 0

Views: 83

Answers (2)

David D
David D

Reputation: 1591

The answer to your question is: they are compiler dependent in certain situations, and not in others. Details within

If you need to extract data from a class, and compact it to a minimum format, I suggest implementing a set of serialize/deserialize methods for them. If you are just trying to figure out what c++ does, the question linked should help a lot.

Upvotes: 1

user2059014
user2059014

Reputation:

This would be safer

size_t off = offsetof( Derived1, a );
Derived1 obj;

unsigned* unsafe_internal_a = (unsigned*)((char *)(&obj) + off);

Upvotes: 0

Related Questions