5.5. Static Objects

Objects that you declare inside functions and blocks reside in a function's stack frame. The following code, for instance, creates a local Fifo object inside a function.

void sub() {
   Fifo f(100);               // local Fifo in stack frame
   . . .
}

The compiler generates code to allocate memory for f in sub()'s stack frame before calling the Fifo constructor. Likewise, the compiler calls the Fifo destructor before releasing memory from sub()'s stack frame when we return from sub(). Thus, local objects use stack frame memory, and the compiler calls constructors and destructors automatically.

To place objects into free store instead of a function's stack frame, we use operators new and delete.

 void sub() { . . . Fifo *pf = new Fifo(100); ...

Get Navigating C++ and Object-Oriented Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.