What is "this" pointer ? Illustrate with example.

Sep 15, 2018

this pointer is a pointer that points to the object itself, with which the mumber function is associated; meaning that, this pointer borns for every non-static member function of the class. When the function is invoked then,  this pointer comes into existance with the value of the address of the object through which it is called. this pointer is also called magic pointer.

It can be Illustrated by the folloing program.

// program to demonstrate the use of 
//this pointer, 

#include<iostream>
using namespace std;

class Complex{
	private:
		float real;
		float imag;
	public:
		Complex(float f = 0, float i = 0){
			// member access with -> operator
			this->real = f;
			this->imag = i;
		}
		// this function conjugates the complex number
		// also, this function returns the conjugate
		Complex getConjugate(){
			// member access with . operator
			(*this).imag = - (*this).imag;
			return *this;
		}
		void display(){
			cout<<"("<<(*this).real<<", "<<(*this).imag<<")"<<endl;
		}
};


int main(){
	Complex c1(3.3,5.5),c2;
	cout<<"Before operation:"<<endl;
	c1.display();
	c2.display();
	c2 = c1.getConjugate();
	cout<<"After operation:"<<endl;
	c1.display();
	c2.display();
	return 0;
}

 

Sample Run:

Before operation:
(3.3, 5.5)
(0, 0)
After operation:
(3.3, -5.5)
(3.3, -5.5)

 

Related


Tools/Apps





© Nepal Exchange Rates