From what i know, the size of a class in c++ depends on the below factors -
Now I've created 2 classes as below -
class A{ int a; short s; int b; char d; };// kept a char at last on purpose to leave a "hole" class B : public A{ char c; };
now on checking the size of A and B I see
my assumption is the char c in class B is accommodated in "hole" left in class A.
But, whats confused me is the below scenario wherein I make the members public
class A{ public: int a; short d; int b; char s; }; class B : public A{ public: char c; };
Now the size becomes
I cannot seem to understand the reason for this difference.
The class members declared as private can be accessed only by the functions inside the class. The data members and member functions declared public can be accessed by other classes too. Only the member functions or the friend functions are allowed to access the private data members of a class.
So as objects are data only, it calculate size by adding all the sizes of data members of a class. Member functions are common for all the objects, it only differ by the first argument of the particular objects pointer (called this pointer) which is passed as the hidden pointer to every member function of the class.
public - members are accessible from outside the class. private - members cannot be accessed (or viewed) from outside the class. protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.
private data members are generally considered good because they provide encapsulation. Providing getters and setters for them breaks that encapsulation, but it's still better than public data members because there's only once access point to that data.
The Itanium ABI uses the C++03 definition of POD to define classes that are "POD for the purposes of layout". Having private data members disqualifies a class from being an aggregate and therefore POD in C++03:
A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor.
Being a POD class disables tail padding reuse:
The dsize, nvsize, and nvalign of these types are defined to be their ordinary size and alignment. These properties only matter for non-empty class types that are used as base classes. We ignore tail padding for PODs because an early version of the standard did not allow us to use it for anything else and because it sometimes permits faster copying of the type.
Thus, in your first example, A
is not a POD for layout purposes and its tail padding can be used for B::c
, but in your second example, it is a POD, and its tail padding cannot be reused.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With