LOGBOOK

HELP

Quiz Entry - updated: 2026.07.14

How do you create an object on the heap in C++?

Use new: Vehicle *v = new Vehicle(4); — it returns a pointer you must later free with delete v;.

Stack allocation freed automatically at scope end versus heap allocation needing an explicit delete

* Stack objects clean themselves up at scope end; heap objects live until you delete them yourself — miss it and you leak. *

int main() {
    Vehicle *v = new Vehicle(4);   // allocate on the heap
    v->show();                     // arrow notation for pointer access
    delete v;                      // free the memory (and run the destructor)
    return 0;
}

Key differences from stack allocation:

Stack Heap
Vehicle v(4); Vehicle *v = new Vehicle(4);
v.show(); v->show();
Auto cleanup Must delete v; yourself

Tip: Every new needs a matching delete, or you leak memory. In modern C++, prefer smart pointers (unique_ptr, shared_ptr) which delete for you automatically.

Go deeper:

From Quiz: REVE1 / C++ Programming | Updated: Jul 14, 2026