Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

#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 class Father like this:

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

sizeof(Child)=8

like image 476
user478937 Avatar asked Dec 25 '22 20:12

user478937


2 Answers

It's an implementation detail of the compiler. In other words, not really your business, unless you really, really need to make your data as small as possible. Beware premature optimization here.

In the end, it probably comes down to peculiarities of the Common C++ ABI, using terms like "POD for the purpose of layout" and "base class padding reuse".

Edit: Or not, because those pragmas suggest you're using Visual Studio. In that case, never forget that the MS ABI is a jungle of wild backwards compatibility hacks.

like image 103
Sebastian Redl Avatar answered Mar 01 '23 22:03

Sebastian Redl


The difference in size you are seeing is a result of the compatibility to C. C only knows about struct where everything is public. So, when you use public members in a C++ struct or class, the ABI is compatible with C, hence it needs to follow the alignment rules of C.

When you declare the members private, the C++ ABI has more freedom to optimize the packing of the members.

like image 34
Daniel Frey Avatar answered Mar 01 '23 23:03

Daniel Frey