DIGITAL ELECTRONIC

‘this’ is a reserved keyword in c++. It is used to get the variables or member functions present in the current class. ‘this’ pointer is not available for the friend functions because they are not members of class.

It is given as an implicit argument to the member functions.

Let’s see the code below to understand more about this pointer.

#include <iostream>
using namespace std;
class personal_details {
    private:
       string name,address;
       int age,salary;

    public:
    
       void input_details(string name,string address,int age,int salary){
         this->name = name; 
         /*On the left side name is the argument which is passed in the input_details functions and 
         On the right side name is a private variable of personal_details class.
         We can assign similarly for other arguments also.*/
         this->address = address;
         this->age = age;
         this->salary = salary;
       } 

       void display_details() {
         cout << "The name of person is "<< name <<"\n";
         cout << "Age of " << name << " is: " << age <<"\n";
         cout << "Salary of " << name << " is: " << salary <<"\n";
         cout << "Address of " << name << " is: " << address <<"\n";
       }
};

int main() {
    personal_details obj;
    
    obj.input_details("Lucy", "35 B Wall Street", 25, 25000);
    
    obj.display_details();
    
    return 0;
}

Output:

The name of person is Lucy

Age of Lucy is: 25

Salary of Lucy is: 25000

Address of Lucy is: 35 B Wall Street

So whenever we write ‘this’ pointer it implies that the variable or member function is from the current class in which the code is running.

The post this Pointer in C++ appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3kdccxW

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget