Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between this->variable and namespace::class::variable in C++?

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?

like image 680
user2452253 Avatar asked Sep 12 '26 12:09

user2452253


2 Answers

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).

like image 111
Sergey Kalinichenko Avatar answered Sep 14 '26 01:09

Sergey Kalinichenko


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;
}
like image 41
Daerst Avatar answered Sep 14 '26 03:09

Daerst