11

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?

Bryan Peeters
  • 161
  • 10
  • 2
    Of course, if `bar` is a virtual function instead of a data member, there's a difference between the two. Also note you can combine them like `this->Foo::bar`. – dyp Apr 27 '13 at 22:21

4 Answers4

12

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
  }
};
Jon
  • 428,835
  • 81
  • 738
  • 806
4

They do the same thing members.

However, you wont be able to use this-> to distinguish members of the same name in the class hierarchy. You will need to use the ClassName:: version to do that.

pmr
  • 58,701
  • 10
  • 113
  • 156
0

For what I have learned fiddling around with C/C++, using the -> on something is mainly for a pointer object, and using :: is used for the classes that are part of a namespace or super class that is the general class of whatever you're including

user2277872
  • 2,963
  • 1
  • 21
  • 22
  • Well, for the :: it is like using std::cout << ""; Using :: means that you are using the direct implementation of the std namespace instead of saying using namespace std; in your file. The -> is like you are "pointing" a pointer to another object. That is how i have seen them used. – user2277872 Apr 27 '13 at 22:22
0

It also allows you you to reference variable of another class (base class in most cases) with the same name. For me it's obvious from this example, hope it'll helps you.

#include <iostream>
using std::cout;
using std::endl;

class Base {
public:
    int bar;
    Base() : bar(1){}
};

class Derived : public Base {
public:
    int bar;

    Derived() : Base(), bar(2) {}

    void Test() {
        cout << "#1: " << bar << endl; // 2
        cout << "#2: " << this->bar << endl; // 2
        cout << "#3: " << Base::bar << endl; // 1
        cout << "#4: " << this->Base::bar << endl; // 1
        cout << "#5: " << this->Derived::bar << endl; // 2
    }
};

int main()
{
    Derived test;
    test.Test();
}

This is because the real data stored in class is like this:

struct {
    Base::bar = 1;
    Derived::bar = 2; // The same as using bar
}
Vyktor
  • 20,559
  • 6
  • 64
  • 96