ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Home » C++ programming language

C++ 'this' pointer

In C++ programming language 'this' is a keyword, the value of 'this' pointer is the address of object in which the member function is called.

Type of 'this' pointer is "Class pointer" (or "Objet pointer") type - if there is a class named "Example" then, the type of 'this' pointer will be "Example*".

Its type may depends on member function declaration in which the 'this' pointer is used. If the member function is declared as const, volatile or const volatile - the type of 'this' pointer will be const Example*, volatile Example* or const volatile Example* respectively.
(Reference: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf)

Use of 'this' when local variables and class data members are same (while defining a member function)

#include <iostream>
using namespace std;

class Number
{
	private:
		int a;
	public:
		void get_a(int a)
		{this->a=a;}
		void put_a()
		{cout<<"a= "<<a<<endl;}
};

int main()
{
	Number N;
	N.get_a(36);
	N.put_a();
	return 0;
}
    a= 36

Here, a is the local variable of member function get_a() and also class member data type. Statement this->a=a; copies the value of a (local variable) in the class data member a.

ADVERTISEMENT

Use of ‘this’ to return the reference to the calling object

'this' pointer can be used to return the reference of current/calling object, here is an example where an object is being initialized with another object using parameterized constructor.

#include <iostream>
using namespace std;

class Number
{
	private:
		int a;
	public:
		//default constructor
		Number(){this->a=0;}
		//parameterized constructor
		Number (Number &n)
		{
			this->a=n.a;
		}
		void get_a(int a)
		{this->a=a;}
		void put_a()
		{cout<<"a= "<<a<<endl;}
		Number &set()
		{
			return *this;
		}
};

int main()
{
	Number N1;
	N1.get_a(36);
	cout<<"N1..."<<endl;
	N1.put_a();
	
	Number N2(N1.set());
	cout<<"N2..."<<endl;
	N2.put_a();
	return 0;
}
    N1...
    a= 36
    N2...
    a =36

Here, statement Number N2(N1.set()); is initializing the value of a of object N2 with the value of a of object N1.

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.