How are objects stored in memory in C++?

前端 未结 5 1515
無奈伤痛
無奈伤痛 2020-12-03 02:18

How are objects stored in memory in C++?

For a regular class such as

class Object
    {
public:
    int i1;
    int i2;
    char i3;
    int i4;
pri         


        
5条回答
  •  庸人自扰
    2020-12-03 02:43

    Classes without virtual members and without inheritance are laid out in memory just like structs. But, when you start getting levels of inheritance things can get tricky and it can be hard to figure out what order things are in memory (particularly multiple inheritance).

    When you have virtual members, they have a "vtable" in memory which contains pointers to the actual function which gets created based on the inheritance hierarchy of the class.

    The bottom line is: don't access classes this way at all if you can avoid it (and also don't memset them or memcpy them). If you must do this (why?) then take care that you know exactly how your class objects are going to be in memory and be careful to avoid inheritance.

提交回复
热议问题