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