Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope resolution :: vs this ->

Tags:

c++

oop

this

I am trying to understand pointers and scope in OOP with C++. Is there any difference at all between:

class Class 
{  
public:
    void setVal (int value) { 
        this -> value = value;
    }
    int getVal();
private:
     int value;
};

and this:

class Class 
{  
public:
    void setVal (int value) {
        Class::value = value;  
    }  
    int getVal();
private:
    int value;
};
like image 798
Jeff-Russ Avatar asked Oct 31 '22 09:10

Jeff-Russ


1 Answers

The two pieces of code you posted have identical behaviour, but not because A->B and A::B ever mean the same thing.

  • this->value is, sort of, short for this->Class::value, because class Class is searched first for value
  • Class::value is, sort of, short for this->Class::value, because the current object is assumed when referring to a member variable without this->.

The this-> means "give me something that's a part of this particular object I'm talking to you from, please"; the Class::value means "give me the thing called Class::value, please".

This logic doesn't quite apply to member functions, because specifying Class:: yourself turns off virtual dispatch. So this->foo() is not the same as this->Class::foo().

like image 190
Lightness Races in Orbit Avatar answered Nov 15 '22 05:11

Lightness Races in Orbit