简体   繁体   中英

Multiple inheritance same method name and no ambiguity

I have two classes (A0 and A1) that have a function foo() and a A0 has a function bar() that just calls foo(). And a class B that inherits from A0 and A1.

B does nothing beside inheriting from A0 and A1.

Why is there no ambiguity when calling B->bar() ?

A small code sample

class A0
{
protected:
    /*virtual*/ void foo() {std::cout << "A0" << std::endl; }
public:
    void bar() {foo(); }
};

class A1
{
protected:
    /*virtual*/ void foo() {std::cout << "A1" << std::endl; }
};

class B : public A0, public A1
{
protected:
    //virtual void foo() override {A1::foo(); }
};

int main()
{
    B *lPtr = new B;
    lPtr->bar(); //"A0" without the override, "A1" with the override
    delete lPtr;

    return 0;
}

And if I uncomment the virtual and the function override, there is still no ambiguity but it calls the other foo.

Why is there still no ambiguity and why does it call the other one?

In the case you have virtual there are two foo s in your vtable.

The first one is A0::foo the second one is A1::foo .

When you override foo in B , you override both , and instruct it to call A1::foo() .

If you don't override foo in B , the two foo s remain in the vtable, unrelated except by name.

In A0::bar , when you call foo() it looks locally for a foo . It sees one -- A0::foo -- which is virtual. So it encodes a call into the vtable to execute A0::foo .

Without the override in B the invokes A0::foo . With the override in B this invokes B::foo when then calls A1::foo instead.

In the case you don't have virtual , well, the same holds except the vtable bit.

You have two functions A0::foo and A1::foo . With a pointer to A0 , ->foo() invokes A0::foo .

With a pointer to B , ->foo() is ambiguous.

If you write a B::foo method (does not matter if it is virtual), then B->foo() invokes it.


The fact that two things share a name doesn't mean they are the same thing, nor does it make all calls ambiguous.

The calls are ambiguous only if you cannot tell which one is being named from context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM