Bird
Raised Fist0
C++programming~10 mins

Object lifecycle in C++ - Step-by-Step Execution

Choose your learning style10 modes available
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++.
Execution Sample
C++
#include <iostream>
class MyClass {
public:
  MyClass() { std::cout << "Constructor\n"; }
  ~MyClass() { std::cout << "Destructor\n"; }
};

int main() {
  MyClass obj;
}
This code creates an object of MyClass, calls its constructor, then calls its destructor when main ends.
Execution Table
StepActionOutputObject State
1Enter main functionNo object
2Declare obj of MyClassConstructorObject created
3Use obj (no output here)Object alive
4Exit main functionDestructorObject destroyed
💡 Program ends, destructor called, object lifecycle complete
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4
objNot declaredConstructedAliveDestroyed
Key Moments - 3 Insights
Why do we see 'Constructor' printed before 'Destructor'?
The constructor runs when the object is created (Step 2), and the destructor runs when the object goes out of scope at the end of main (Step 4), as shown in the execution_table.
Does the destructor run automatically or do we call it?
The destructor runs automatically when the object is destroyed (Step 4). We do not call it manually, as shown by the output in the execution_table.
What happens if we declare the object inside a block?
The constructor runs when declared, and the destructor runs when the block ends, similar to Steps 2 and 4 but earlier. The lifecycle is the same but scoped to the block.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of 'obj' after Step 3?
AObject destroyed
BObject alive
CObject not declared
DConstructor running
💡 Hint
Check the 'Object State' column for Step 3 in the execution_table.
At which step does the destructor run according to the execution_table?
AStep 4
BStep 3
CStep 2
DDestructor never runs
💡 Hint
Look at the 'Output' column for the destructor call in the execution_table.
If we remove the object declaration, what output will the program produce?
AConstructor and Destructor
BOnly Constructor
CNo output
DOnly Destructor
💡 Hint
Without object declaration, constructor and destructor are not called, so no output appears.
Concept Snapshot
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
Full Transcript
This example shows the lifecycle of an object in C++. When the object 'obj' is declared in main, the constructor runs and prints 'Constructor'. The object stays alive during the main function. When main ends, the destructor runs automatically and prints 'Destructor'. This shows how C++ manages object creation and destruction automatically based on scope.

Practice

(1/5)
1. Which of the following best describes when a destructor is called for an automatic (local) object in C++?
easy
A. When the object is created
B. When the object goes out of scope
C. When the program starts
D. Only when the object is deleted manually

Solution

  1. Step 1: Understand automatic object lifecycle

    Automatic objects are created when their scope starts and destroyed when their scope ends.
  2. Step 2: Identify destructor call timing

    The destructor is called automatically when the object goes out of scope to clean up resources.
  3. Final Answer:

    When the object goes out of scope -> Option B
  4. Quick Check:

    Destructor called at scope end = When object goes out of scope [OK]
Hint: Destructor runs automatically at scope end for local objects [OK]
Common Mistakes:
  • Thinking destructor runs at object creation
  • Believing manual deletion is needed for local objects
  • Confusing program start with object destruction
2. Which of the following is the correct syntax to declare a destructor for a class named Car in C++?
easy
A. void Car();
B. destructor Car();
C. Car::~Car();
D. ~Car();

Solution

  1. Step 1: Recall destructor syntax

    Destructor syntax uses a tilde (~) followed by the class name and parentheses.
  2. Step 2: Match correct option

    ~Car(); matches the correct syntax: ~Car();
  3. Final Answer:

    ~Car(); -> Option D
  4. Quick Check:

    Destructor syntax = ~ClassName() [OK]
Hint: Destructor always starts with ~ followed by class name [OK]
Common Mistakes:
  • Using void return type for destructor
  • Writing destructor with class scope resolution in declaration
  • Using keyword 'destructor' which doesn't exist
3. What will be the output of the following C++ code?
class Test {
public:
  Test() { std::cout << "Created "; }
  ~Test() { std::cout << "Destroyed "; }
};

int main() {
  Test t1;
  {
    Test t2;
  }
  return 0;
}
medium
A. Created Created Destroyed Destroyed
B. Created Destroyed Created Destroyed
C. Created Created Destroyed
D. Destroyed Created Created Destroyed

Solution

  1. Step 1: Trace object creation

    First, t1 is created: prints "Created ". Then inside inner scope, t2 is created: prints another "Created ".
  2. Step 2: Trace object destruction

    When inner scope ends, t2 is destroyed: prints "Destroyed ". Then at program end, t1 is destroyed: prints "Destroyed ".
  3. Final Answer:

    Created Created Destroyed Destroyed -> Option A
  4. Quick Check:

    Constructor and destructor calls match output [OK]
Hint: Objects destroyed in reverse order of creation at scope end [OK]
Common Mistakes:
  • Assuming destruction happens immediately after creation
  • Forgetting inner scope destruction before outer
  • Mixing order of constructor and destructor prints
4. Consider the following code snippet:
class Sample {
public:
  Sample() { std::cout << "Start "; }
  ~Sample() { std::cout << "End "; }
};

int main() {
  Sample* p = new Sample();
  // Missing delete p;
  return 0;
}

What is the problem with this code?
medium
A. Syntax error due to missing delete
B. Destructor is called twice causing error
C. Memory leak because destructor is not called
D. No problem, code runs fine

Solution

  1. Step 1: Identify dynamic object creation

    The object is created with new, so it lives on the heap and needs manual deletion.
  2. Step 2: Check for destructor call

    Since delete p; is missing, destructor is never called, causing a memory leak.
  3. Final Answer:

    Memory leak because destructor is not called -> Option C
  4. Quick Check:

    Missing delete on new object = memory leak [OK]
Hint: Always delete dynamically allocated objects to call destructor [OK]
Common Mistakes:
  • Assuming destructor runs automatically for new objects
  • Thinking missing delete causes syntax error
  • Believing destructor is called twice
5. You want to track how many objects of class Box currently exist during program execution. Which approach correctly uses constructors and destructors to maintain this count?
hard
A. Increment a static counter in constructor and decrement it in destructor
B. Increment a global variable in constructor only
C. Decrement a static counter in constructor and increment in destructor
D. Use constructor to print count and destructor to reset count

Solution

  1. Step 1: Understand object counting logic

    To track live objects, increase count when object is created and decrease when destroyed.
  2. Step 2: Use static counter in class

    A static variable shared by all objects can hold the count, incremented in constructor and decremented in destructor.
  3. Final Answer:

    Increment a static counter in constructor and decrement it in destructor -> Option A
  4. Quick Check:

    Static counter + constructor increment + destructor decrement = correct count [OK]
Hint: Use static variable incremented in constructor, decremented in destructor [OK]
Common Mistakes:
  • Changing count only in constructor or destructor, not both
  • Using global variable instead of static class member
  • Reversing increment and decrement roles
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard