This Pointer in C++ with simple example program

This Pointer in C++ with simple example program

Before knowing about 'this' pointer in C++, let us first know about the object pointer, what an object pointer is and what are its benefits.


Object pointer in C++

A pointer containing address of an object is called object pointer.

For Example:-
#include<iostream>
using namespace std;
class Box
{
int length, breadth, height;

public:
void setData(int l, int b, int h) //instance member function.
{
length = l;
breadth = b;
height = h;
}

void showData() //instance member function.
{
cout<<"\nLength= "<<length;
cout<<"\nBreadth= "<<breadth;
cout<<"\nHeight= "<<height;
}
};

int main()
{
Box *P
Box smallBox;

P=&smallBox; //P is an object pointer.

P->setData(10,25,11);
P->showData();
}


This pointer in C++

1. 'this' is a keyword in C++.
2. 'this' is a local object pointer in every instance member function containing address of the caller object.
3. 'this' pointer cannot be modified.
4. 'this' is used to refer caller object in member function.
5. 'this' pointer is used to solve the problem of name conflict.


For Example:-
#include<iostream>
using namespace std;
class Box
{
int length, breadth, height;

public:
void setDimension(int length, int breadth, int height) //instance member function.
{
this->length = length;
this->breadth = breadth;
this->height = height;
}

void showDimension() //instance member function.
{
cout<<"\nLength= "<<length;
cout<<"\nBreadth= "<<breadth;
cout<<"\nHeight= "<<height;
}
};

int main()
{
Box *P
Box smallBox;

P=&smallBox; //P is an object pointer.

P->setDimension(10,25,11);
P->showDimension();
}


<< Previous                                                                                      Next >>
Previous
Next Post »