Use of c++ this pointer

What is 1.this pointer?
2. Where is this pointer?
What is the main purpose of 3.this pointer?

======================================================
1. As the name implies, this pointer is a pointer variable, which points to the current object itself. That is, in c++, every object can access its address through this pointer.
Such as:

#include <iostream>
using namespace std;

class C_Dog{

public:

      C_Dog()
      { 
      	  cout <<this<<endl;
      }
      
  };
int main()
{
	C_Dog wangcai;
}

2. Since every object can access its address through this, does this mean that this pointer itself is an invisible member variable in the class? To verify this conjecture, you can determine the size of the space occupied by the print class. After printing, you will find that this is not the case. The real existence of this pointer is passed in as an implicit parameter of each member function. That is, in the above code, the constructor is not without parameters, but has an invisible parameter, pointing to the current object address pointer.

C_Dog(C_Dog  * pointer){
		C_Dog *this = pointer;               //This is invisible.
}

Whenever a member function is called, the address of the current object is passed in.

What does 3.this pointer do?
(1) Avoid membership function form participating in the same name of member variables.
(2) Implementing chain assignment expression

#include <iostream>
using namespace std;

class C_Dog{

public:

      C_Dog(string color,int age)
      { 
        this->age = age;
        this->color = color;
        cout <<this<<endl;
      }
      void bark()
      {
           cout <<"wanwanwan" <<endl;
      }
    string get_color(string &color)
     {

        color  = this->color;
       

     }

    void  get_age(int &age)
     {

        age = this->age;
       

     }

    //  C_Dog * grow()
    //  {

    //    age++;
    //    return  this;
    //  }
//The above is to return the address of the current object directly.
//Writing two:
      C_Dog grow()
      {

        age ++;
        cout<<this<<endl;
        return *this;
      }

//The above writing will cause problems. Why?

//Modified writing
      // C_Dog & grow()
      // {

      //   age ++;
      //   return *this;
      // }

private:

        string color;
        int age;
        
};


int main()
{

  C_Dog wangcai("red",4);
  //cout<<&wangcai<<endl;

  wangcai.bark();
  string color; 
  wangcai.get_color(color);
  int age;
  cout << color << endl;
  //Implementing chain assignment expression
 // wangcai.grow()->grow()->grow();

  wangcai.grow().bark();

  wangcai.get_age(age);
  cout << age << endl;

}

Posted by eddy666 on Thu, 03 Oct 2019 01:04:21 -0700