Lesson 12 of 19
Destructors
Destructors
A destructor is a special member function that runs when an object is destroyed — when it goes out of scope or is explicitly deleted. Its name is the class name prefixed with ~.
Syntax
class File {
private:
string name;
public:
File(string n) {
name = n;
cout << "Opened " << name << endl;
}
~File() {
cout << "Closed " << name << endl;
}
};
When a File object goes out of scope, the destructor runs automatically:
{
File f("data.txt");
} // "Closed data.txt" printed here
RAII — Resource Acquisition Is Initialization
C++ uses the RAII pattern: acquire resources in the constructor, release them in the destructor. This guarantees cleanup even if an exception occurs.
class Connection {
public:
Connection() { cout << "Connected" << endl; }
~Connection() { cout << "Disconnected" << endl; }
};
Destruction Order
Objects are destroyed in reverse order of their construction:
File a("first");
File b("second");
// destructor order: b, then a
Rules
- A destructor takes no parameters and has no return type
- Each class has exactly one destructor
- If you don't write one, the compiler generates a default that does nothing special
- Always write a destructor if your class manages a resource (memory, file handle, network socket)
Your Task
Create a Logger class that:
- Has a
private string name - Constructor takes a name, stores it, and prints
"Logger <name> created" - Destructor prints
"Logger <name> destroyed" - Has a
log(string msg)method that prints"[<name>] <msg>"
Create two loggers, log a message with each, then call their destructors in reverse order.
JSCPP loading...
Loading...
Click "Run" to execute your code.