Assignment Oop
Assignment Oop
Assignment # 02
What is a destructor? Write its syntax and rules, and provide an
example?
Answer:
A destructor is a special member function of a class in object-oriented
programming. It is automatically called when an object is destroyed or goes out of scope. The
main purpose of a destructor is to free resources that were allocated to the object during its
lifetime, such as memory, file handles, or database connections.
Syntax of destructor:
The destructor has the same name as the class, preceded by a tilde (~).
A destructor does not take any arguments and does not return a value.
Syntax code:
class ClassName {
public:
~ClassName() {
// Destructor code
};
class ClassName {
public:
1|Page
Subject name: Object oriented programming
~ClassName(); // Destructor declaration
};
ClassName::~ClassName() {
// Destructor code
Note:
Similar to constructor, the destructor name should exactly match with the class name. A
destructor declaration should always begin with the tilde(~) symbol as shown in the syntax
above.
#include <iostream>
class HelloWorld{
public:
//Constructor
HelloWorld(){
cout<<"Constructor is called"<<endl;
//Destructor
~HelloWorld(){
cout<<"Destructor is called"<<endl;
}
2|Page
Subject name: Object oriented programming
//Member function
void display(){
cout<<"Hello World!"<<endl;
};
//Object creation
int main(){
//Object created
HelloWorld obj;
obj.display();
return 0;
Output:
Constructor is called
Hello World!
Destructor is called
#include <iostream>
class FileHandler {
3|Page
Subject name: Object oriented programming
public:
// Constructor
FileHandler() {
if (file) {
// Destructor
~FileHandler() {
if (file) {
fclose(file);
private:
FILE* file;
};
int main() {
4|Page
Subject name: Object oriented programming
}
Explanation of code:
This ensures that resources (such as file handles) are properly released when the object is no
longer needed.
Destructor rules:
1) Name should begin with tilde sign (~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a default destructor
and inserts it into your code.
5|Page