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?
this means the object of Foo on which DoSomething() is invoked. I explain it with example
and our class
now we instantiate objects like
similarly whatever the string will be passed to Foo constructor will be printed on calling DoSomething().
Because for example in DoSomething() of above example "this" means fooObject and in do_something_to_a_foo() fooObject is passed by reference.
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 calledthis
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:
When you compile and run this, observe that the value of
this
is different betweena1
anda2
.Just some random facts about
this
to supplement the other answers:When the object is
const
, the type ofthis
becomes a pointer toconst
.The
this
pointer can be used to access a member that was overshadowed by a function parameter or a local variable.Multiple inheritance will cause the different parents to have different
this
values. Only the first inherited parent will have the samethis
value as the derived object.this
refers to the current object.The keyword
this
identifies a special type of pointer. Suppose that you create an object namedx
ofclass A
, andclass A
has a non-static member functionf()
. If you call the functionx.f()
, the keywordthis
in the body off()
stores the address ofx
.this is a pointer to self (the object who invoked this).
Suppose you have an object of class Car named car which have a non static method getColor(), the call to this inside getColor() returns the adress of car (the instance of the class).
Static member functions does not have a this pointer(since they are not related to an instance).
this
is a pointer that points to the object for whichthis
function was called. For example, the function callA.max()
will set the pointerthis
to the address of the object. The pointerthis
is acts as an implicit argument to all the member functions.You will find a great example of
this
pointer here. It also helped me to understand the concept. http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/