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?
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.
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.
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.
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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With