Using the this pointer to differentiate between member data and parameters

suggest change

This is an actual useful strategy to differentiate member data from parameters… Lets take this example :

#include <iostream>
#include <string>

using std::cout;
using std::endl;

class Dog
    Dog(std::string name);
    void  bark() const;
    std::string  getName() const;
    std::string name;

Dog::Dog(std::string name)
    *  this->name is the
    *  name variable from 
    *  the class dog . and
    *  name is from the 
    *  parameter of the function
    this->name = name; 


void Dog::bark() const
  cout << "BARK" << endl;   

std::string  Dog::getName() const
    return this->name;

int main()
    Dog dog("Max");
    cout << dog.getName() << endl;

You can see here in the constructor we execute the following:

this->name = name;

Here , you can see we are assinging the parameter name to the name of the private variable from the class Dog(this->name) .

To see the output of above code :

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents