Why is the "this" pointer used to call derived member functions?

Viewed 167

While reading a tutorial about virtual functions(not relavant for this example) on this link, I found this code.

class Weapon
{
    public:
      void features()
         { cout << "Loading weapon features.\n"; }
};



class Bomb : public Weapon
{
    public:
       void features()
         { 
            this->Weapon::features(); 
            cout << "Loading bomb features.\n"; 
         }
};

The class Weapon is derived by the class Bomb, where the member function of Weapon is called.

Why is the function Weapon::features() called with the "this" pointer? Isn't this already implicit given?

1 Answers

The this is implicitly given, and it is often a matter of style whether to write it explicitly or not. In your case I'd say that it does not improve readability.

In other cases, however, it makes sense or is even necessary to explicitly write this in order to avoid naming conflicts between local variables and data members. Consider, for example, the following program:

class SomeClass {
public:
    void print(int amount) const {
        cout << amount << endl;
    }
    int amount = 10;
};

int main() {
    SomeClass c;
    c.print(20);
}

The output is 20, an if one wanted to access the data member, one would have to write cout << this->amount << endl. Yes, bad style, maybe. But in a technical sense an explicit this sometimes is even required.

Related