user997112
user997112

Reputation: 30635

Memory locations of classes (refers to Inside the C++ object model book)

I am currently reading Inside the C++ Object Model. On page 9 it has a diagram showing how the contents of a class are laid out in memory. It states the only part of an object which actually resides in the class memory are non-static data members.

Here is a post from SO regarding the contents of memory for a program:

Global memory management in C++ in stack or heap?

In the second answer it details the memory layout of a program- showing the stack and the heap.

Does the location of the static data members/any class function (basically the parts of the class which are not stored within the object- referring to page 9) change depending whether the object is on the stack or the heap?

Upvotes: 3

Views: 1611

Answers (2)

jxh
jxh

Reputation: 70472

Static data members reside in the same area of memory that global variables and plain static variables would reside. It is the "class memory" that could either be on the stack or heap, depending on how the instance of the class was created.

A static data member is not too different from a global variable. However, it is scoped by the class name, and its access by name can be controlled via public, private, and protected. public gives access to everyone. private would restrict access to only members of the class, and protected is like private but extends access to a class that inherits from the class with the static data member.

In contrast, a global variable is accessible by name by everyone. A plain static variable is accessible by name by code in the same source file.

A plain class method is actually just a regular function (modulo access controls), but it has an implicit this parameter. They do not occupy any space in a class. However, a virtual class method would occupy some memory in the class, since it has to resolve to a derived class's implementation of the method. But, polymorphism is likely not yet covered where you are in your textbook.

Upvotes: 4

Bo Persson
Bo Persson

Reputation: 92321

No, where variables are allocated doesn't affect the storage of static data or code. These are generally stored in separate memory areas, that are neither stack or heap.

Functions and static data members are special in that that there is only one copy of each in the whole program.

Variables of class, or other, types are most often created and destroyed multiple times during a program run.

Upvotes: 2

Related Questions