Object Oriented Programing MSc.
Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
Destructor in C++
What is a destructor?
Destructor is a special member function of a class that is executed whenever an object of its class
goes out of scope or whenever the delete expression is applied to a pointer to the object of that
class.
Destructor name is same as class name but preceded by (~)
For example if name of constructor is integer()
Then destructor is ~integer()
Characteristics of Destructor
1. It never takes any argument ////no parameters
2. Only one destructor is need to destroy.
3. Compiler automatically makes destructor.
Simple example for destructor
#include<iostream>
using namespace std;
class gabs
public:
gabs()
cout<< " Constrctor of gabs" <<endl; ////constructor
~gabs()
1
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
cout<< " Destrctor of gabs" <<endl; ////Destructor
};
int main()
gabs g1,g2();
return 0;
////////////////////////////////////////////////////////////////////////
Example 2
#include <iostream>
using namespace std;
class Rectangle
private:
int length;
int width;
public:
Rectangle() // Constructor
cout << "Constructor" << endl;
2
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
~Rectangle() // Destructor
cout << "Destructor" << endl;
void setDimension(int l, int b)
length = l;
width = b;
int getArea()
return length * width;
};
int main()
Rectangle rt;
[Link](7, 4);
cout << [Link]() << endl;
return 0;
3
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
Friend Function
What is a Friend Function in C++?
A friend function in C++ is defined as a function that can access private, protected and a public
member of a class.
The friend function is declared using the friend keyword inside the body of the class.
4
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
5
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
Example 3:
#include <iostream>
using namespace std;
class boss {
int salary;
public:
boss() //// default constructor
{}
6
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
boss(int a) /////parameter constructor
salary=a;
void display()
cout<<"Boss salary="<<salary<<endl;
friend void salary(boss); // friend function
};
int main()
boss b(5000);
[Link]();
return 0;