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 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:
new expression — cppreference — what
newreally does: allocate, then construct.new and delete — Wikipedia — the allocation pair explained with examples.