Search Your Topic

config
Tuesday, 13 June 2017 12:42

C++ this Pointer

Written by
Rate this item
(0 votes)

 

 

In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++.

  • It can be used to pass current object as a parameter to another method.
  • It can be used to refer current class instance variable.
  • It can be used to declare indexers.

C++ this Pointer Example

Let's see the example of this keyword in C++ that refers to the fields of current class.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. class Employee {  
  4.    public:  
  5.        int id; //data member (also instance variable)      
  6.        string name; //data member(also instance variable)  
  7.        float salary;  
  8.        Employee(int id, string name, float salary)    
  9.         {    
  10.              this->id = id;    
  11.             this->name = name;    
  12.             this->salary = salary;   
  13.         }    
  14.        void display()    
  15.         {    
  16.             cout<<id<<"  "<<name<<"  "<<salary<<endl;    
  17.         }    
  18. };  
  19. int main(void) {  
  20.     Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee   
  21.     Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee  
  22.     e1.display();    
  23.     e2.display();    
  24.     return 0;  
  25. }  

Output:

101  Sonoo  890000
102  Nakul  59000

 

Read 549 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in
More in this category: « C++ Destructor C++ static »

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.