user8424470
user8424470

Reputation:

How can class definitions not occupy memory?

So I have read this about if class definitions occupy memory and this about if function occupy memory. This is what I do not get: How come class definitions do not occupy memory if functions do, or their code does. I mean, class definitions are also code, so shouldn't that occupy memory just like function code does?

Upvotes: 4

Views: 2250

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

You don't need to keep the class definition anywhere, because the details of how to create an instance of a class are encoded in its constructors.
(In a sense, the class definition is code, it's just not represented explicitly.)

All you need to know in order to create an object is

  1. How big it is,
  2. Which constructor to use for creating it, and
  3. Which its virtual functions are.

To create an instance of class A:

  1. Reserve a piece of memory of size sizeof(A) (or be handed one),
  2. Associate that piece of memory with the virtual functions of A, if any (usually held in a table in a predetermined location), and
  3. Tell the relevant A constructor where the A should be created, and then let it do the actual work.

You don't need to know a thing about the types of member variables or anything like that, the constructors know what to do once they know where the object is to be created.
(Every member variable can be found at an offset from the beginning of the object, so the constructor knows where things must be.)

To create a function, on the other hand, you would need to store its definition in some form and then generate the code at runtime. (This is usually called "Just-in-time" compilation.)

This requires a compiler, which means that you need to either

  1. Include a compiler in every executable, or
  2. Provide (or require everyone to install) a shared compiler for all executables (Java VMs usually contain at least one).

C++ compilers instead generate the functions in advance.
Abusing terminology a little, you could say that the functions are "instantiated" by the compilation process, with the source code as a blueprint.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

It is not entirely correct to say that class definitions do not occupy memory: any class with member functions may place some code in memory, although the amount of code and its actual placement depends heavily on function inlining.

The Q&A at the first link talks about sizeof, which shows a per-instance memory requirement of the class, which excludes memory requirements for storing member functions, static members, inlined functions, dispatch tables, and so on. This is because all these elements are shared among all instances of the class.

Upvotes: 5

Related Questions