0Pricing
C++ Academy · Lesson

Object Lifetime

When objects are created and destroyed.

When Objects Are Born

An object's lifetime begins after its storage is allocated and its constructor finishes. From that point it is fully usable.

#include <iostream>

struct Widget {
    Widget() { std::cout << "born\n"; }
};

int main() {
    Widget w;   // constructor runs here
}

When Objects Die

Lifetime ends when the destructor runs. For a stack object that happens at the closing brace of its scope.

#include <iostream>

struct Widget {
    ~Widget() { std::cout << "dies\n"; }
};

int main() {
    Widget w;
    std::cout << "alive\n";
}   // ~Widget runs here

All lessons in this course

  1. Stack Allocation
  2. Heap Allocation with new/delete
  3. Object Lifetime
  4. Common Memory Bugs
← Back to C++ Academy