Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

inheritance - C++: Accessing parent methods and variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...