Search code examples
c++classpointersthisscope-resolution

Difference between this->field and Class::field?


I'm wondering something in C++.

Admitting the following code:

int bar;
class Foo
{
public:
    Foo();
private:
    int bar;
};

Inside my class, is there any difference between this->bar and Foo::bar? Are there cases where one is invalid?


Solution

  • Inside class Foo (specifically) there is no difference between the two given that bar is not static.

    Foo::bar is called the fully qualified name of the member bar, and this form is useful in scenarios where there may be several types in the hierarchy defining a member with the same name. For example, you would need to write Foo::bar here:

    class Foo
    {
      public: Foo();
      protected: int bar;
    };
    
    class Baz : public Foo
    {
      public: Baz();
      protected: int bar;
    
      void Test()
      {
          this->bar = 0; // Baz::bar
          Foo::bar = 0; // the only way to refer to Foo::bar
      }
    };