chrise chrise - 2 months ago 8
C++ Question

c++ class difference between this and class::

My understanding is that if I have a class

class MyClass {
public:
MyClass();
void SetVal( int );
private:
int val_;
}


I can reference a member

MyClass::SetVal( int val ) { val_ = val }

MyClass::SetVal( int val ) { MyClass::val_ = val }

MyClass::SetVal( int val ) { this->val_ = val }


I like the idea of indicating that a variable is a class member.
Is there any difference between the second and the third approach?

EDIT: made SetVal( int ) public. Been sloppy in writing down the example. Thanks for pointing out

Answer

There is actually a difference!... Its a name lookup thing

This,

MyClass::SetVal( int val ) { val_ = val }

does an unqualified name lookup. where val_ is first searched in class scope first, if not found, name-lookup proceeds to search global namespace for val_. An example here


This,

MyClass::SetVal( int val ) { MyClass::val_ = val }

does a qualified name lookup. where val_ it is strictly limited to class namespace. so if you do not have such member val_, it wouldn't go further searching global namespace. Another example here


This,

MyClass::SetVal( int val ) { this->val_ = val }

is similar to the second. example here


Just to add, the style of the second (using scope resolution) can be used to disambiguate same names. See this question

Comments