Home Uncategorized Write a program to illustrate this pointer.

Write a program to illustrate this pointer.

SHARE

AIM: Write a C++ program to illustrate this pointer

THEORY:

The ‘this’ pointer is a pointer accessible only within the non-static member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.

this

this->member-identifier

An object’s this pointer is not part of the object itself; it is not reflected in the result of a sizeof statement on the object. Instead, when a non-static member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function. For example, the following function call:

myDate.setMonth( 3 );

can be interpreted this way:

setMonth( &myDate, 3 );

The object’s address is available from within the member function as the this pointer. Most uses of this are implicit. It is legal, though unnecessary, to explicitly use this when referring to members of the class.

SOURCE CODE:

#include<iostream>
using namespace std;
class name
{
   char str[15];
   int age;
   public:
   void input()
   {
      cout<<“Enter name and age:”<<endl;
      cin>>str;
      cin>>age;
   }
   void show()
   {
      cout<<str<<“\t”<<age<<endl;
   }
   name display(name x)
   {
      cout<<this->str;
      cout<<“\t”<<this->age<<endl;
      cout<<x.str<<“\t”;
      cout<<x.age<<endl;
      if(this->age>x.age)
         return *this;
      else
         return x;
   }
};
int main()
{
   name n,n1,n2;
   n1.input();
   n2.input();
   n=n1.display(n2);
   cout<<“Older one is\n”;
   n.show();
}

OUTPUT:

Enter name and age:
HARI      96
Enter name and age:
VENU    93
HARI      96
VENU    93
Older one is
HARI      96

Back to Programs.