c++ – How is memory allocated for classes, is it allocated when the class is defined?


How is memory allocated for classes, is it allocated when defining a class and when creating an object of a class?


Memory allocation can be divided into two broad categories:

  1. Memory allocated at the compilation stage: objects whose contents are known at the compilation stage (constants), machine code of functions, various service information, such as tables of virtual methods, tables with type information, tables of exception handlers, etc. All this goes into the executable file and memory for this is all immediately allocated by the system when the application starts.

  2. Run-time memory: objects whose contents are not known at compile time. In this case, memory allocation can be determined by:

    1. Compiler – for all objects with storage time automatic, static, thread local (that is, created without the new operator).

    2. By the programmer – for all objects with dynamic storage time (that is, created using the new operator). In this case, again, two options are possible:

      1. Memory is allocated using a global or overloaded memory allocation function (the usual syntax of the new operator).

      2. No memory allocation occurs, the object is placed in the specified existing buffer (syntax placement new).

Scroll to Top