Order of Constructor and Destructor Execution

Medium Object Lifecycle (Constructors & Destructors)
Solve in Playground →

Problem Statement

Create a `Widget` class taking an integer ID. Print ‘C[ID]’ in the constructor and ‘D[ID]’ in the destructor. In `main()`, create `w1` with ID 1, then `w2` with ID 2. Observe the creation and destruction order.

Input Format

None

Output Format

Print the sequence of C[ID] and D[ID] outputs.

Constraints

None

Sample Output

C1
C2
D2
D1

Explanation

Constructors execute in order of creation (FIFO), but destructors execute in reverse order (LIFO) as variables are popped off the stack.

Starter Code

#include <iostream>

class Widget {
    // Implement ID, constructor, and destructor
};

int main() {
    // Create w1(1) and w2(2)
    return 0;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used