Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in C++ the size of a class must be always known by its users?

Let's say that a class is completely defined in its .cpp file, so that in the source file you can find:

  • The constructor defined
  • The desctructor defined
  • Every method defined

Than why its private member variables must still be in the header file? Why do we still need PIMPL to get rid of them?

If for this class I also define its own new operator in the source file, why I still need to know the size from the outside code?

Is it because the class can be still stack allocated? If so, than why the "function" who allocates on the stack is not part of the constructor call inside the .cpp file?

like image 658
nyarlathotep108 Avatar asked Dec 02 '25 09:12

nyarlathotep108


1 Answers

Than why its private member variables must still be in the header file? Why do we still need PIMPL to get rid of them?

Because for many operations - those allowed after a definition's been seen - the compiler needs to know the size of object instances. Further details below.

If for this class I also define its own new operator in the source file, why I still need to know the size from the outside code?

Is it because the class can be still stack allocated? If so, than why the "function" who allocates on the stack is not part of the constructor call inside the .cpp file?

Partly. It's simplest and most efficient for the compiler to move the stack pointer by the total size of local variables as a function call starts, then move it back as it returns. That size can normally be calculated at compile time. If you had runtime functions returning the individual object sizes, then the compiler would need to handle the stack pointer deltas in dribs and drabs, and either repeatedly calculate the address of specific objects at runtime as the cumulative total of earlier allocations, or use memory/registers to maintain a set of pointers or offsets to wherever they end up. (This is one of the main reasons most C++ compilers don't support runtime specification of array dimensions.)

I say "partly" because it's not just about the stack: similar issues apply to static / global and thread-local objects.

like image 51
Tony Delroy Avatar answered Dec 05 '25 00:12

Tony Delroy