2

Is it safe to assume that the fields of an object are always in order of their definition when that object is dinamicly allocated?

Example that worked for me:

struct Rectangle
{
    int len;
    int wid;
};

Rectangle* myRect = new Rectangle;
void* vPtr = myRect;

Will *(int*)(vPtr) be always equivalent to myRect->len and *(int*)(vPtr + sizeof(int)) equivalent to myRect->wid?

Will the same thing happen for this case too?

class Button
{
     Rectangle* frame;
     Char* Text;
} *myButton;
void * vButton = myButton;

Will *(int*)((*Rectangle)(vButton)) be the field len ?

Because i don't want a big book as an answer i will ask the following question. When i have a more classes like this:

#define WND_BUTTON 1
#define WND_EDIT   2
class Button
{
    private:
        BYTE TypeWindow;
        SMALL_RECT srFrame;
        *Some other fields*
    public:
        Button();
        *Just functions here*
}
class Edit
{
    private:
        BYTE TypeWindow;
        SMALL_RECT srFrame;
        /*Some other fields*/
    public:
        Edit();
        /*Just functions here*/
}

typedef void* HANDLE;

Can i rely on this check ?

HANDLE hWindow = Create(...);

if (*(BYTE*)(hWindow) == WND_BUTTON)
    std::cout<<"This is a button."<<std:endl;
if (*(BYTE*)(hWindow) == WND_EDIT)
    std::cout<<"This is a text field."<<std:endl;
Hydra Zerg
  • 47
  • 5
  • The fields will be in order, in two groups - `static` members will be in order, and non-static members will be in order. Alignment may play a role in the rest of your questions. – Sid S May 24 '18 at 03:54
  • 2
    Possible duplicate of [Do class/struct members always get created in memory in the order they were declared?](https://stackoverflow.com/questions/281045/do-class-struct-members-always-get-created-in-memory-in-the-order-they-were-decl) – Joseph D. May 24 '18 at 03:54
  • And that duplicate will tell you it depends on the compiler's packing, and that you should not depend on this. – Stewart Smith May 24 '18 at 03:55
  • According to the answer in the link that @codekaizer gave, access specifiers matter so in the example with private: and public: even the standard says that the order of the items is unspecified. – Jerry Jeremiah May 24 '18 at 04:56

0 Answers0