I come from C programming where the data in a struct is laid out with the top variable first, then the second, third and so on..
I am now programming in C++ and I am using a class instead. I basically want to achieve the same, but I also want get/set methods and also maybe other methods (I also want to try do it in a C++ style and maye learn something new).
Is there a guarantee e.g. that the public variables will be first in memory then the private variable?
First thing first:
class
andstruct
in C++ are very much the same - the only difference is that all members before the first access specifier in aclass
are considered private, while in astruct
they are public.There is no such guarantee. When there is no inheritance, the memory will be allocated to class members in the order in which you declare them within the same access group. It is up to the compiler to decide if the public member variables should be placed ahead of the private / protected ones or vice versa. Like C, C++ can add padding in between class members.
Inheritance makes things more complicated, because data members of the base class need to be placed within the derived class as well. On top of that, there is virtual inheritance and multiple inheritance, with complex rules.
If you make all data members of your class private, and add accessor member functions (that's what C++ calls "methods" from other languages) you would achieve this effect.
No, such a guarantee is not made - C++11 standard, [class.mem]/14:
So
It is only guaranteed that, for a given object of type
A
,i
has a smaller address thanj
andj
has a smaller address thanstr
Note that the class-keys
struct
andclass
have no difference regarding layout whatsoever: Their only difference are access-rights which only exist at compile-time.Yes, but only for standard-layout classes. There is a row of requirements a class must satisfy to be a standard-layout class, one of them being that all members have the same access-control.
Quoting C++14 (the same applies for C++11, but the wording is more indirect), [class.mem]/19:
[class]/7: