Consider this:
I have a class with some private variables and some public methods e.g. setters or constructors. When I'm implementing the methods, does it make any difference to say this->variable = 0; or namespace::class::variable = 0;?
in header (example.h):
namespace spc
{
class MyClass
{
public:
MyClass();
private:
int variable;
int variable2;
};
}
now in the cpp file (example.cpp) I have:
spc::MyClass::MyClass()
{
spc::MyClass::variable = 0;
this->variable2 = 0;
}
This will compile. And also in the application source, constructing and object of this class will have both variables with value 0 (assuming I have some getters as well). So my question is: are these two lines of code any different from each?
This will compile
spc::MyClass::variable = 0;
this->variable2 = 0;
That's right! But this will also compile, producing the same result:
variable = 0;
variable2 = 0;
In general, this-> and scope resolution :: operator are there for you to instruct the compiler which variable to use when there is any ambiguity. For example, a constructor parameter may have the same name as a member variable:
spc::MyClass::MyClass(int variable2)
{
this->variable2 = variable2;
}
Here, the use of this-> differentiates between variable2-the-parameter and variable2-the-member of spc::MyClass.
In the absence of ambiguity, however, using "plain" variable names is "idiomatic" to the language.
Note: One difference between MyClass::something and this->something is when something is a virtual member function; the former will suppress the virtual call mechanism, while the later will not (thanks, Sebastian Redl, for a great comment).
The following statements are equal:
spc::MyClass::MyClass()
{
// Very uncommon
spc::MyClass::variable = 0;
// Use this for clarity, if you feel the need
this->variable = 0;
// Short and common
variable = 0;
}
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