I made a simple class to represent a door. To return the variables, I'm accessing them with the this
pointer. With respect to just accessing variables, what's the difference between accessing them with the this
pointer and without?
class Door
{
protected:
bool shut; // true if shut, false if not shut
public:
Door(); // Constructs a shut door.
bool isOpen(); // Is the door open?
void Open(); // Opens the door, if possible. By default it
// is always possible to open a generic door.
void Close(); // Shuts the door.
};
Door::Door()
{}
bool Door::isOpen()
{
return this->shut;
}
void Door::Open()
{
this->shut = false;
}
void Door::Close()
{
if(this->isOpen()) this->shut = true;
}
There may or may not be a difference here, but what about for more complex classes?
Nothing. The this
pointer is automatically added if you exclude it.
You only have to use it if you're doing something like this:
void Door::foo(bool shut)
{
this->shut = shut; // this is used to avoid ambiguity
}
More usages
A brief overview:
Think of methods as functions that pass a pointer as their first argument.
void Door::foo(int x) { this->y = x; } // this keyword not needed
is roughly equivilent to
void foo(Door* this_ptr, int x) { this_ptr->y = x; }
Methods just automate this.
There's no difference.
When you write sane C++, you shouldn't have to say this
at all except in very specific situations. (The only ones I can think of are binding pointers-to-member-function, passing the instance pointer to some other object, and some situations involving templates and inheritance (thanks to Mooing Duck for that last example).)
Just give your function arguments and local variables and member variables sensible names so that you don't get any ambiguities.
There's a slew of more recent quasi-object-oriented languages which have made the words "this" and "new" all but synonymous with "I'm using objects" for younger generations, but that is not the C++ idiom.
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