Wednesday, March 28, 2018

Write a C++ program to illustrate this pointer


AIM: Write a C++ program to illustrate this pointer
THEORY:
The latest version of this topic can be found at this Pointer.
The this pointer is a pointer accessible only within the nonstatic 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 nonstatic 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<<"\n Enter name and age:"<<endl<<endl;
                        cin>>str;
                        cin>>age;
                        }         
                        void show()
{
                                    cout<<str<<age;
                        }
                        name display(name x)
                        {
                                    cout<<this->str;
                                    cout<<this->age;
                                    cout<<x.str;
                                    cout<<x.age;
                                    if(this->age>x.age)
                                    return *this;
                                    else
                                    return x;
                        }
};
int main(){
            name n,n1,n2;
            n1.input();
            n2.input();
            n=n1.display(n2);
            n.show();
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home