0
0
C++programming~5 mins

Object lifecycle in C++

Choose your learning style9 modes available
Introduction

Objects in C++ have a life from creation to destruction. Understanding this helps you manage memory and program behavior well.

When you create a variable or object in your program.
When you want to know when resources like memory are allocated or freed.
When debugging why an object's data changes or disappears.
When writing classes with constructors and destructors.
When managing dynamic memory with pointers.
Syntax
C++
class ClassName {
public:
    ClassName() { /* constructor code */ }
    ~ClassName() { /* destructor code */ }
};

// Creating an object
ClassName obj;

// Object is destroyed automatically when it goes out of scope

The constructor runs when an object is created.

The destructor runs when the object is destroyed (goes out of scope or deleted).

Examples
This example shows messages when the object is created and destroyed automatically.
C++
#include <iostream>

class Box {
public:
    Box() { std::cout << "Box created\n"; }
    ~Box() { std::cout << "Box destroyed\n"; }
};

int main() {
    Box b;
    return 0;
}
The object b is destroyed when the function ends.
C++
#include <iostream>

class Box {
public:
    Box() { std::cout << "Box created\n"; }
    ~Box() { std::cout << "Box destroyed\n"; }
};

void createBox() {
    Box b;
    std::cout << "Inside function\n";
}

int main() {
    createBox();
    std::cout << "Back in main\n";
    return 0;
}
When using new, you must delete to destroy the object and free memory.
C++
#include <iostream>

class Box {
public:
    Box() { std::cout << "Box created\n"; }
    ~Box() { std::cout << "Box destroyed\n"; }
};

int main() {
    Box* b = new Box();
    // use b
    delete b; // manually destroy the object
    return 0;
}
Sample Program

This program shows when the Person object is created and destroyed inside a block.

C++
#include <iostream>

class Person {
public:
    Person() { std::cout << "Person created\n"; }
    ~Person() { std::cout << "Person destroyed\n"; }
};

int main() {
    std::cout << "Start main\n";
    {
        Person p;
        std::cout << "Inside block\n";
    }
    std::cout << "End main\n";
    return 0;
}
OutputSuccess
Important Notes

Objects created inside a block are destroyed when the block ends.

Dynamic objects created with new must be deleted manually to avoid memory leaks.

Constructors and destructors help manage setup and cleanup automatically.

Summary

Objects have a lifecycle: creation (constructor) and destruction (destructor).

Automatic objects are destroyed when they go out of scope.

Dynamic objects need manual deletion to free memory.