AIM: Write a C++ program to illustrate this pointer.
THEORY:
The ‘this’ pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
For a class X, the type of this pointer is ‘X* const’. Also, if a member function of X is declared as const, then the type of this pointer is ‘const X *const’
SOURCE CODE:
#include<iostream>
using namespace std;
class name
{
char str[15];
int age;
public:
void input()
{
cout<<“Enter name and age:\n”;
cin>>str;
cin>>age;
}
void show()
{
cout<<“Name: “<<str<<endl;
cout<<“Age: “<<age;
}
name display(name x)
{
cout<<this->str<<endl;
cout<<this->age<<endl;
cout<<x.str<<endl;
cout<<x.age<<endl;
if(this->age>x.age)
{
return *this;
}
else
{
return x;
}
}
};
int main()
{
name n1,n2,n;
n1.input();
n2.input();
n=n1.display(n2);
cout<<”Older one is:\n”;
n.show();
return 0;
}
OUTPUT:
Enter name and age:
Harisha 35
Enter name and age:
Shamshad 34
Older one is:
Name: Harisha
Age: 35