8. Destructor

#include <iostream>
using namespace std;

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

int main() {
    Device d;
    return 0;
}

 

Solution Explanation

  • Device() (constructor) runs when the object is created.
  • ~Device() (destructor) runs automatically at the end of the scope.
     

Layman’s Terms

The constructor is like switching ON a device, and the destructor is like switching it OFF when you’re done.

 

Significance for Embedded Developers

This mirrors RAII (Resource Acquisition Is Initialization) in embedded firmware:

  • Constructor can open/configure hardware.
  • Destructor can release or reset hardware when done (e.g., turning off a peripheral safely).

     
Loading...

Input

Expected Output

Device created Device destroyed