I need to understand this
pointer concept, preferably with an example.
I am new to C++, so please use simple language, so that I can understand it better.
The this pointer is a pointer accessible only within the nonstatic member functions of a class , struct , or union type. It points to the object for which the member function is called. Static member functions don't have a this pointer.
The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.
The this pointer in C++ points to the object that invokes the member function. This keyword is only accessible within the nonstatic member functions of a class/struct/union type. There are many ways to use the this pointer.
"delete this" in C++? Delete is an operator that is used to Deallocate storage space of Variable. This pointer is a kind of pointer that can be accessed but only inside nonstatic member function and it points to the address of the object which has called the member function.
this
is a pointer to an instance of its class and available to all non-static member functions.
If you have declared a class, which has a private member foo
and a method bar
, foo
is available to bar
via this->foo
but not to "outsiders" via instance->foo
.
The this
pointer is used in a class to refer to itself. It's often handy when returning a reference to itself. Take a look at the proto-typical example using the assignment operator:
class Foo{
public:
double bar;
Foo& operator=(const Foo& rhs){
bar = rhs.bar;
return *this;
}
};
Sometimes if things get confusing we might even say
this->bar = rhs.bar;
but it's normally considered overkill in that situation.
Next up, when we're constructing our object but a contained class needs a reference to our object to function:
class Foo{
public:
Foo(const Bar& aBar) : mBar(aBar){}
int bounded(){ return mBar.value < 0 ? 0 : mBar.value; }
private:
const Bar& mBar;
};
class Bar{
public:
Bar(int val) : mFoo(*this), value(val){}
int getValue(){ return mFoo.bounded(); }
private:
int value;
Foo mFoo;
};
So this
is used to pass our object to contained objects. Otherwise, without this
how would be signify the class we were inside? There's no instance of the object in the class definition. It's a class, not an object.
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