Skip to main content

Department class constructor and destructor

Short answer

The Department class constructor initializes ID and name, printing a creation message. The destructor prints a destruction message. In main(), three objects are created; upon going out of scope, destructors run in reverse order: d3, d2, d1 are destroyed, confirming LIFO order.

Write a program that can store Department ID and Department name with constructor. Also write destructor in the same class and show that objects are destroyed in reverse order of creation with suitable message.

A destructor has the class name preceded by ~, takes no arguments and has no return type. It is called automatically when an object goes out of scope. For automatic (local) objects, destructors run in the reverse order of construction, since the stack unwinds last-in-first-out.

#include <iostream>
#include <cstring>
using namespace std;

class Department
{
    int id;
    char name[30];
public:
    Department(int i, const char *n)       // constructor
    {
        id = i;
        strcpy(name, n);
        cout << "Constructor: " << name << " (ID " << id << ") created\n";
    }
    void display()
    {
        cout << "ID: " << id << ", Name: " << name << endl;
    }
    ~Department()                          // destructor
    {
        cout << "Destructor: " << name << " (ID " << id << ") destroyed\n";
    }
};

int main()
{
    Department d1(1, "Computer");
    Department d2(2, "Civil");
    Department d3(3, "Electronics");
    d1.display();
    d2.display();
    d3.display();
    return 0;       // destructors run here
}

Output

Constructor: Computer (ID 1) created
Constructor: Civil (ID 2) created
Constructor: Electronics (ID 3) created
ID: 1, Name: Computer
ID: 2, Name: Civil
ID: 3, Name: Electronics
Destructor: Electronics (ID 3) destroyed
Destructor: Civil (ID 2) destroyed
Destructor: Computer (ID 1) destroyed

The objects d1, d2, d3 are created in that order but destroyed as d3, d2, d1, showing reverse order of destruction.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →