What is the proper way of accessing a member data/function that is part of the method's class? There appears to be 3 means:
class test{
private:
int variable;
public:
void setVariable(int value) {
variable = value; // method 1, using the variable name directly
this->variable = value; // method 2, via pointer dereference of 'this'
test::variable = value; // method 3, via scope operator
}
};
They all seems to work as far as I can tell. Are they equivalent? Is there a reason to use one over the other beside style/consistency?
In addition to style and consistency, as you mention, sometimes you have to use a specific syntax to disambiguate.
"method 2" can be used to disambiguate between local variables and class members.
"method 3" can be used to disambiguate between fields with the same name in different places of your class hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With