×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

C++ 'this' pointer

In this tutorial, we will learn about this pointer in C++, its usage, and examples.

What is 'this' pointer in C++?

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.

Types of 'this' Pointer

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)

Example: Use of "this" when local variables and class data members are same

#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;
}

Output

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.


Example: 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;
}

Output

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.

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.