If definition stands for assigning memory. How come a class definition in C++ has no memory assigned until an object is instantiated.
C++ Class definitions do not assign memory. class
is like typedef
and struct
. Where did you get the idea that "definition stands for assigning memory"? Can you provide a quote or reference?
C++ Object creation (via new
) assigns memory.
The class definition gets compiled down into code. That code is part of the process image. The process image does get loaded into RAM (and hence uses up memory) by your operating system, but it is not part of your process' usable memory space.
When you create an object of your class, you are using memory in your process' usable memory space. The process' usable memory space is composed of memory at one of 2 places. The stack or the heap.
No memory is taken up for class definitions on the stack nor heap. When you create an object of a class it will always go on either the stack or heap.
If you define is as a pointer to a class, C++ does not automatically allocate memory to the object. In C++ the memory management has to be done in your code which has benefits and drawbacks depending on the use case of your application.
Class* test;
The above will not allocate memory, it defaults to pointing to nothing.
Class test;
The above will be usable, but it will have local scope.
Class declaration tells the compiler and runtime how much memory to allocate for each class instance, but only when requested. Class definition produces the executable code for class behavior.
A class definition has nothing to do with memory assignment. It is kind of a blueprint for the construction process where an instance of the specified type is created.
class A
{
unsigned char number;
};
class A contains a member with the size of 1 Byte. If you create an instance of that class 1 Byte of memory will be needed.
This is true up to a point. All classes and stucts in C/C++ have 2 places with "names" in them.
Class <Name>
{
...
}<Vars>;
What you do is define <Vars> variables of Class <Name>. All the Vars will have memory allocated for them, but what you usually do, is omit the <Vars> part, and you get an empty definition of variables, like writing
int;