C++ The This Pointer Using the this Pointer to Differentiate Between Member Data and Parameters


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

// Dog Class Example
#include <iostream>
#include <string>

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

* @class Dog
*   @member name
*       Dog's name
*   @function bark
*       Dog Barks!
*   @function getName
*       To Get Private
*       Name Variable
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 : http://cpp.sh/75r7