C++ Constructors and Object Lifetime
This is the first part of C++ OOP basics.
Series navigation: Previous: Constructor series | Next: Constructor overload and delegating constructors
The goal is simple:
- create an object
- see when the constructor runs
- see when the destructor runs
- compare stack and heap lifetime
Class
A class groups data and functions together.
Constructor
A constructor runs when the object is created.
In this example, the constructor receives the name and stores it in name_.
Destructor
A destructor runs when the object lifetime ends.
Use the destructor to release resources owned by the object.
Stack object
Stack objects are automatic.
The constructor runs when execution reaches the object definition. The destructor runs automatically when the scope ends.
Heap object
Heap objects created with new live until you call delete.
The constructor runs on new. The destructor runs on delete.
Modern C++ usually prefers smart pointers instead of raw new and delete.
This first part uses raw pointers only to show the object lifetime clearly.
Full example
Expected output:
Run online
Copy the full example above and run it in the embedded OneCompiler C++ runtime.
Run locally
Save the example as main.cpp:
Series navigation: Previous: Constructor series | Next: Constructor overload and delegating constructors