C++: Accessing parent methods and variables

user542687 picture user542687 · Dec 24, 2010 · Viewed 26.8k times · Source

In which way should I access this parent method and parent variable?

class Base
{
public:
    std::string mWords;
    Base() { mWords = "blahblahblah" }
};

class Foundation
{
public:
    Write( std::string text )
    {
        std::cout << text;
    }
};

class Child : public Base, public Foundation
{
    DoSomething()
    {
        this->Write( this->mWords );
        // or
        Foundation::Write( Base::mWords );
    }
};

Thanks.

Edit: And what if there is ambiguity?

Answer

AnT picture AnT · Dec 24, 2010

The two syntaxes you use in your code (this->... and qualified names) are only necessary specifically when there is ambiguity or some other name lookup issue, like name hiding, template base class etc.

When there's no ambiguity or other problems you don't need any of these syntaxes. All you need is a simple unqualified name, like Write in your example. Just Write, not this->Write and not Foundation::Write. The same applies to mWords.

I.e. in your specific example a plain Write( mWords ) will work just fine.


To illustrate the above, if your DoSomething method had mWords parameter, as in

DoSomething(int mWords) {
  ...

then this local mWords parameter would hide inherited class member mWords and you'd have to use either

DoSomething(int mWords) {
  Write(this->mWords);
}

or

DoSomething(int mWords) {
  Write(Foundation::mWords);
}

to express your intent properly, i.e. to break through the hiding.


If your Child class also had its own mWords member, as in

class Child : public Base, public Foundation
{
  int mWords
  ...

then this name would hide the inherited mWords. The this->mWords approach in this case would not help you to unhide the proper name, and you'd have to use the qualified name to solve the problem

DoSomething(int mWords) {
  Write(Foundation::mWords);
}

If both of your base classes had an mWords member, as in

class Base {
public:
  std::string mWords;
  ...
};

class Foundation {
public:
  int mWords;
  ...

then in Child::DoSomething the mWords name would be ambiguous, and you'd have to do

DoSomething(int mWords) {
  Write(Foundation::mWords);
}

to resolve the ambiguity.


But, again, in your specific example, where there's no ambiguity and no name hiding all this is completely unnecessary.