I am trying to understand pointers and scope in OOP with C++. Is there any difference at all between:
class Class
{
public:
void setVal (int value) {
this -> value = value;
}
int getVal();
private:
int value;
};
and this:
class Class
{
public:
void setVal (int value) {
Class::value = value;
}
int getVal();
private:
int value;
};
The two pieces of code you posted have identical behaviour, but not because A->B and A::B ever mean the same thing.
this->value is, sort of, short for this->Class::value, because class Class is searched first for value
Class::value is, sort of, short for this->Class::value, because the current object is assumed when referring to a member variable without this->.The this-> means "give me something that's a part of this particular object I'm talking to you from, please"; the Class::value means "give me the thing called Class::value, please".
This logic doesn't quite apply to member functions, because specifying Class:: yourself turns off virtual dispatch. So this->foo() is not the same as this->Class::foo().
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