Concept Flow - Object lifecycle
Object Declaration
Constructor Called
Object in Use
Destructor Called
Object Destroyed
This flow shows how an object is created, used, and then destroyed in C++.
#include <iostream> class MyClass { public: MyClass() { std::cout << "Constructor\n"; } ~MyClass() { std::cout << "Destructor\n"; } }; int main() { MyClass obj; }
| Step | Action | Output | Object State |
|---|---|---|---|
| 1 | Enter main function | No object | |
| 2 | Declare obj of MyClass | Constructor | Object created |
| 3 | Use obj (no output here) | Object alive | |
| 4 | Exit main function | Destructor | Object destroyed |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|
| obj | Not declared | Constructed | Alive | Destroyed |
Object lifecycle in C++: - Object declared -> constructor runs - Object used while alive - Object destroyed -> destructor runs - Constructor and destructor manage setup and cleanup - Destructor runs automatically at scope end
Car in C++?~Car();class Test {
public:
Test() { std::cout << "Created "; }
~Test() { std::cout << "Destroyed "; }
};
int main() {
Test t1;
{
Test t2;
}
return 0;
}t1 is created: prints "Created ". Then inside inner scope, t2 is created: prints another "Created ".t2 is destroyed: prints "Destroyed ". Then at program end, t1 is destroyed: prints "Destroyed ".class Sample {
public:
Sample() { std::cout << "Start "; }
~Sample() { std::cout << "End "; }
};
int main() {
Sample* p = new Sample();
// Missing delete p;
return 0;
}new, so it lives on the heap and needs manual deletion.delete p; is missing, destructor is never called, causing a memory leak.Box currently exist during program execution. Which approach correctly uses constructors and destructors to maintain this count?Pass the test and this pattern moves unknown