Is calling this function ambiguous?

I learn about multiple inheritance and the diamond problem, and when I call the function call from the derived class itself, Visual Studio tells me that the call is ambiguous:

struct A
{
    virtual void aFunction() { cout << "I am A\n"; }
};
struct B : A {};
struct C : A {};
struct D : B, C {};

int main()
{
   D DObj;
   DObj.aFunction();             //  This is an ambiguous call
}

I understand that if I redefined the base class function in classes B and C, then the call would be ambiguous, but is not "aFunction ()" the same in B and C?

In addition, turning B and C into inheritance with A actually leads to an error. But my understanding of the keyword "virtual" in inheritance, i.e. (Derived: virtual Base), is that it prevents the "more derived class" further down the chain from inheriting multiple copies of Base up the chain. In inheritance, multiple copies of member variables can be inherited, but only one copy of a function with the same name. So, for example, I could have 5 derived classes, each of which was based on Base, and then on MostDerivedClass, inheriting all 5 Derived classes, in MostDerivedClass I would have 5 instances of the base classes "member variables", but only one copy functions with the same name.

, , "" "Member variable". , .

EDIT: , . " " A D, A ( ). , ++ , , , 1. " " A D, .

+4
3

, A, this . , , , this, , , .

virtual , A, .

+5

- , .

struct A
{
    int x;
    virtual void aFunction() { cout << "I am A with value " << x ; }
};
struct B : A {
};
struct C : A {
};
struct D : B, C {};

int main()
{
   D DObj;
   ((B*)(&DObj))->x = 0; // set the x in B to 0
   ((C*)(&DObj))->x = 1; // set the x in C to 1
   DObj.aFunction();             //  This is an ambiguous call
}

0 1?

, , , .

+2

use virtual inheritance to solve diamond span:

struct A
{
    int x;
    virtual void aFunction() { cout << "I am A with value " << x ; }
};
struct B : virtual A { // add virtual
};
struct C : virtual A { // virtual
};
struct D : B, C {};
0
source

Source: https://habr.com/ru/post/1665432/


All Articles