Destructor & Friend Function
Destructor & Friend Function
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.
#include<iostream>
class gabs
public:
gabs()
~gabs()
1
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
};
int main()
gabs g1,g2();
return 0;
////////////////////////////////////////////////////////////////////////
Example 2
#include <iostream>
class Rectangle
private:
int length;
int width;
public:
Rectangle() // Constructor
2
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
~Rectangle() // Destructor
length = l;
width = b;
int getArea()
};
int main()
Rectangle rt;
rt.setDimension(7, 4);
return 0;
3
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
Friend Function
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>
class boss {
int salary;
public:
{}
6
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University College
salary=a;
void display()
cout<<"Boss salary="<<salary<<endl;
};
int main()
boss b(5000);
b.display();
return 0;