Destructors:: "This" POINTER
Destructors:: "This" POINTER
In C++, We can have more than one constructor in a class with same name, as long as each has a
different number or type of arguments.This concept is known as Constructor Overloading and is quite
similar to function overloading.
Destructors:
Destructors in C++ are member functions in a class that delete an object. They are called when
the class object goes out of scope such as when the function ends, the program ends, a delete
variable is called etc.
Destructors are different from normal member functions as they don’t take any argument and
don’t return anything.
Also, destructors have the same name as their class and their name is preceded by a tilde(~).
#include<iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
cout<<"Inside Constructor"<<endl;
num1 = n1;
num2 = n2;
}
void display()
{
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
~Demo()
{
cout<<"Memory is deallocated";
}
};
int main() {
Demo obj1(10, 20);
obj1.display();
return 0;
}
“this” POINTER:
C++ uses a unique keyword called “this” to represent an object which invokes a member
function.this is a pointer that points to the object for which this function was called.
The pointer this acts as an implicit argument to all the member functions. Consider the
followingsimple example:
USES:
a = 123;
This->a=123;
2) Another important application of the pointer “this” is to return the object it points to.
For example, the statement
return *this;
This statement is important when we want to compare two or more objects inside a member
function and return the invoking object as a result.
#include <iostream>
#include <cstring>
class Person
char name[20];
float age;
public:
{
strcpy{name,s);
age=a;
If(x.age>= age)
return x ;
else
return *this;
void display(void)
};
Int main()
Person p = P1 . greater(P3);
p.display();
p=p1.greater( p2);
p.display();
return 0;
FRIEND FUNCTION:
It is possible to grant a nonmember function access to the private members of a classby using a
friend. A friend function has access to all private and protected membersof the class for which
it is a friend. To declare a friend function, include its prototypewithin the class, preceding it
with the keyword friend. Consider this program:
#include <iostream>
class myclass {
int a, b;
public:
};
a = i;
b = j;
int sum(myclass x)
{
/* Because sum() is a friend of myclass, it can
int main()
myclass n;
n.set_ab(3, 4);
cout<< sum(n);
return 0;
In this example, the sum( ) function is not a member of myclass. However, it stillhas full access
to its private members. Also, notice that sum( ) is called without the useof the dot operator.
Because it is not a member function, it does not need to be (indeed,it may not be) qualified
with an object's name.
Although there is nothing gained by making sum( ) a friend rather than a memberfunction of
myclass, there are some circumstances in which friend functions are quitevaluable.