Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the 'this' pointer?

I'm fairly new to C++, and I don't understand what the this pointer does in the following scenario:

void do_something_to_a_foo(Foo *foo_instance);


void Foo::DoSomething()
{
  do_something_to_a_foo(this);
}

I grabbed that from someone else's post on here.

What does this point to? I'm confused. The function has no input, so what is this doing?

like image 548
user2371809 Avatar asked May 11 '13 00:05

user2371809


People also ask

What is this pointer in C?

A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.

What is this pointer example?

Another example of using this pointer is to return the reference of current object so that you can chain function calls, this way you can call all the functions for the current object in one go.

What type is this pointer?

In the function f() , the this pointer is of type A* const . The function f() is trying to modify part of the object to which this points. 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.


2 Answers

this refers to the current object.

The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a non-static member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x.

like image 156
TelKitty Avatar answered Sep 22 '22 06:09

TelKitty


The short answer is that this is a special keyword that identifies "this" object - the one on which you are currently operating. The slightly longer, more complex answer is this:

When you have a class, it can have member functions of two types: static and non-static. The non-static member functions must operate on a particular instance of the class, and they need to know where that instance is. To help them, the language defines an implicit variable (i.e. one that is declared automatically for you when it is needed without you having to do anything) which is called this and which will automatically be made to point to the particular instance of the class on which the member function is operating.

Consider this simple example:

#include <iostream>

class A
{
public:
    A() 
    { 
        std::cout << "A::A: constructed at " << this << std::endl;
    } 

    void SayHello()
    {
        std::cout << "Hi! I am the instance of A at " << this << std::endl;
    }
};

int main(int, char **)
{
    A a1;
    A a2;

    a1.SayHello();        
    a2.SayHello();

    return 0;
}

When you compile and run this, observe that the value of this is different between a1 and a2.

like image 23
Nik Bougalis Avatar answered Sep 22 '22 06:09

Nik Bougalis