What is the difference between a private member and a public member in the base class?

#pragma pack(push, 4)
class Father
{
 public:
  int b;
  char c;
};
class Child : public Father
{
  char e;

};
#pragma pack(pop)

SizeOf (father) = 8 SizeOf (child) = 12
 But if we change the class of the Father as follows:

class Father
{
 private:// change from public
  int b;
  char c;
};

SizeOf (child) = 8

+4
source share
3 answers

This is a compiler implementation detail. In other words, it’s not really your business, unless you really need to make your data as small as possible. Beware of premature optimization here.

In the end, it probably comes down to the features of Common C ++ ABI, using terms such as "POD for layout purposes" and "reusing base class add-ons."

: , , Visual Studio. , MS ABI - .

+5

, , C. C struct, . , public ++ struct class, ABI C, C.

private, ++ ABI .

+3

#pragma, , , ; , , , , , wierd ( , ).

, #pragma: g++ ; V++, 12 . , , private public, g++ V++, 8. , : int , Father, Father 8, c. Child ( ) a int, . Child 12: 8 Father, 1 , 3 . V++. ++ - " " ( , ): , , , . , Child e Father + 5 ( Father), , , 6 ( 8 ).

V++ , ; . ( , .) g++ , , , , .

, , - :

Father* p1 = new Child;
Father* p2 = new Child;
memcpy( p2, p1, sizeof(Father) );

may have unexpected consequences, the size of the space actually occupied Father, may be less than sizeof indicated. This may explain the g ++ choice logic: memcpynot valid if the class has private members, so they can apply it; this would be true if all the members (and several other conditions), so they do not apply it in order not to violate such things as above. (Adding a constructor that also makes it memcpyillegal calls g ++ to apply optimization.)

+2
source

Source: https://habr.com/ru/post/1502570/


All Articles