- 2068 Chaitra · 5 marks
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)
Related questions
- Constructor/destructor order; parameterized base constructor · Object Oriented Programming, chapter 6 · asked 2×
- Constructor and destructor order, multilevel inheritance · Object Oriented Programming, chapter 6 · asked 2×
- Department store billing system with files · Object Oriented Programming, chapter 8
- Time class: add two objects · Object Oriented Programming, chapter 1
- Patient information store and retrieve · Object Oriented Programming, chapter 8
- Abstract Student class program · Object Oriented Programming, chapter 7
- Department store 36 × 15 m LED panel lighting · Industrial Power Distribution and Illumination, chapter 7 · asked 3×
- Department store 30 × 15 m twin 55 W LED · Industrial Power Distribution and Illumination, chapter 7 · asked 3×
- Department store 30 × 15 m twin 40 W fluorescent · Industrial Power Distribution and Illumination, chapter 7 · asked 3×
- Student course department class diagram · Object Oriented Analysis and Design, chapter 2