Why don’t C++ class definitions take up memory until an object is created?

0
9
Asked By CuriousCoder93 On

I'm puzzled about how a C++ class definition can remain absent from memory until you actually create an object from it. How can the definition be referenced later on if it's not in memory initially?

4 Answers

Answered By TechieTalker On

A class definition mainly contains the executable code for the member functions and possibly a vtable if you have virtual functions, along with any static members. So, in reality, that code is already in memory. However, if the linker finds out that certain parts are never used, it might skip them. So while the class exists, it doesn’t always occupy memory unless it’s needed.

Answered By MemoryMaster On

When you run a program, all of its instructions are loaded into memory. The class definition is essentially broken down into instructions for creating an object, and that info lives in the code segment of your program. This segment is fixed in size and read-only, separating it from areas where dynamic variables are allocated.

Answered By DevDude92 On

Just to clarify, while the class info technically exists, it doesn't use stack memory unless you're creating an object. It's more about how the creation code is generated at compile time, which means the definition itself doesn’t have to hang around.

Answered By CodeWarrior On

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.