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
{
 public:
    Dog(std::string name);
    ~Dog();
    void  bark() const;
    std::string  getName() const;
 private:
    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; 
}

Dog::~Dog(){}

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

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

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

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

Feedback about page:

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


The this pointer:
* Using the this pointer to differentiate between member data and parameters

Table Of Contents
8 Arrays
11 Loops
39 Streams
49 The this pointer
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype