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?
Since there is no naming conflict, simply use
Write(mWords)
. Use the other 2 if you have local variables that conflict, or when the names are hidden.I think this is the most common approach:
unless you run into ambiguity.
If there's ambiguity or shadowing because you want something in a (particular) base class but something in another base class (or this class) hides it, then use the
Base::name
syntax.If a local variable is shadowing one of your members, then use
this->
, though in general you should try to avoid this situation. (ie: try to avoid naming locals such that they shadow members)I suppose one way to look at it would be to use the first of these that works and does what you want:
name
this->name
Base::name
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. JustWrite
, notthis->Write
and notFoundation::Write
. The same applies tomWords
.I.e. in your specific example a plain
Write( mWords )
will work just fine.To illustrate the above, if your
DoSomething
method hadmWords
parameter, as inthen this local
mWords
parameter would hide inherited class membermWords
and you'd have to use eitheror
to express your intent properly, i.e. to break through the hiding.
If your
Child
class also had its ownmWords
member, as inthen this name would hide the inherited
mWords
. Thethis->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 problemIf both of your base classes had an
mWords
member, as inthen in
Child::DoSomething
themWords
name would be ambiguous, and you'd have to doto resolve the ambiguity.
But, again, in your specific example, where there's no ambiguity and no name hiding all this is completely unnecessary.