In a C ++ class, what's the difference between accessing a member variable using "this"

I made a simple class to introduce the door. To return variables, I refer to them with a pointer this. Regarding easy access to variables, what is the difference between accessing them with thisand without a pointer ?

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;
}

It may not be here, but what about more complex classes?

+5
source share
5 answers

Nothing. A pointer is thisautomatically added if you exclude it.

You need to use it only if you are doing something like this:

void Door::foo(bool shut)
{
    this->shut = shut; // this is used to avoid ambiguity
}

Additional Uses


Short review:

, .

void Door::foo(int x) { this->y = x; } // this keyword not needed

void foo(Door* this_ptr, int x) { this_ptr->y = x; }

.

+10

.

++, this , . (, , - -, , ( Mooing Duck ).)

- , .

-- , "this" "new" , " " , ++.

+3

. .

+1

. , Close :

void Door::Close() {
    shut = true; 
}

, , , , .

(IMO), :

Door(); // Constructs a shut door.

, :

Door::Door()
{}

, ctor shut - true, / .

Worse, your IsOpenseems to bring things back:

bool Door::isOpen()
{
    return this->shut;
}

If it is closed, it does not open and vice versa.

+1
source

There is no difference except the type and noise introduced this->.

void Door::Close()
{
    if(isOpen()) shut = true;
}

more read their following:

void Door::Close()
{
    if(this->isOpen()) this->shut = true;
}

but this is only a personal preference and a matter of style.

0
source

All Articles