Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is purpose of a "this" pointer in C++? [duplicate]

Tags:

c++

pointers

this

What is purpose of this keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this to call peer methods inside a class?

like image 977
de costo Avatar asked May 13 '10 17:05

de costo


People also ask

What is the purpose of this pointer in C?

Pointers are used for file handling. Pointers are used to allocate memory dynamically. In C++, a pointer declared to a base class could access the object of a derived class. However, a pointer to a derived class cannot access the object of a base class.

Where and why does compiler insert this pointer implicitly?

The compiler supplies an implicit pointer along with the names of the functions as 'this'. The 'this' pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions.

What does this -> mean in C++?

The -> is called the arrow operator. It is formed by using the minus sign followed by a greater than sign. Simply saying: To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.

What is the type of this pointer?

The type of the this pointer for a member function of a class type X , is X* const . If the member function is declared with the const qualifier, the type of the this pointer for that member function for class X , is const X* const . A better technique would be to declare member mutable.


1 Answers

Two main uses:

  1. To pass *this or this as a parameter to other, non-class methods.

    void do_something_to_a_foo(Foo *foo_instance);
    
    void Foo::DoSomething()
    {
        do_something_to_a_foo(this);
    }
    
  2. To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.
    MessageBox::MessageBox(const string& message)
    {
      this->message = message;
    }
    (Although an initialization list is usually preferable to assignment in this particular example.)
like image 161
Josh Kelley Avatar answered Nov 16 '22 02:11

Josh Kelley