5 ms·
Unless you explicitly type `virtual`, your C++ classes will have the exact same overhead as C structs. Even with inheritance. The memory layout of struct A
by bstamour 9y ago
Unless you explicitly type `virtual`, your C++ classes will have the exact same overhead as C structs. Even with inheritance. The memory layout of
struct A { int x; };
struct B : A { int y; };
is the same as if you had written
struct B { int x; int y; };
Public/private/protected inheritance and access control do not add overhead. It's literally only if you opt in by typing `virtual` do you get class hierarchy overhead.
- khitchdee 9y agoPublic/private/protected inheritance and access control do not add overhead That's interesting. So does the compiler just put the functions in different parts of the vtable to remember the access control rules. There's no such thing as a free lunch and you're adding information here -- has to be stored somewhere.
- bstamour 9y agoAccess control rules are all checked at compile time. There's literally nothing to store. If you want proof, check the output of your compiler. The only thing a non-virtual struct/class might do is reorder member variables if they're of different access controls, but if you're just using a C-style struct but with private member variables and public non-virtual member functions, it has literally the same memory layout as it would in C.
- khitchdee 9y agoOK. That makes sense. So it's only a compiler overhead