Home > Back-end >  C virtual inheritance ambiguities in question
C virtual inheritance ambiguities in question

Time:10-12

# include
using namespace std;
Class A {
Public:
A (int A) : (A) {x cout<" A constructor... "& lt; Int f () {return + + x; }
~ (A) {cout<" The destructor A... "& lt; Private:
int x;
};
Class B: public virtual A {
Private:
Int y;
A Aobj;
Public:
C B (int a, B int, int) : a (a), (c), y Aobj (c) {cout<" The constructor B... "& lt; Int f () {
A: : f ();
Aobj. F ();
Return + + y;
}
Void the display () {cout~ (B) {cout<" Destructor B... "& lt;
};
Class C: public B {
Public:
C (int a, b int, int) C: b (a, b, C), a (0) {cout<" Constructor C... "& lt; };
Class D: public C, public virtual A {
Public:
D (int a, b int, int) c: c (a, b, c), (c) a {cout<" D constructor... "& lt; ~ D () {cout<" Destructor D... "& lt; };
Int main ()
{
D D (7,8,9);
D.f ();
D.d isplay ();
return 0;
}

D.f in main (); Statement called public inheritance of class D B class f (); Methods and public virtual inheritance in A f (); Why won't produce ambiguity; thank you

CodePudding user response:

Function with the same cover

CodePudding user response:

Because of using the virtual base class

CodePudding user response:

The virtual base class applies to function with the same cover, has nothing to do with virtual inheritance,

Virtual functions is rewritten, a virtual function table, entrance run-time binding operation which function, compile time can also replace the parent class function, the function with the same cover, this has nothing to do with virtual inheritance,

An example produce ambiguity:
Class A {public: int fun () {}};
Class B {public: int fun () {}};
Class C: public A, public {B};

C C;
C.f UN ();//this is ambiguity
So define C, can use function covers the principle of the same name, eliminate ambiguity,
Class C: public A, public B {public: int fun () {}};
C.f UN ();//this is called C functions defined fun



CodePudding user response:

Function with the same cover, impression before B6 will give a warning, but it seems now XE4 didn't this warning?

CodePudding user response:

Inheritance because D C, C inherited B, B virtual inheritance, the base class, then D already exists in A D and virtual inheritance A at this moment, the advantage of the virtual inheritance is save space, to solve multiple inheritance to visit is not clear, so D virtual inheritance is inherited from A class C that, when to visit the D of function, this function does not exist will find it A layer, find will be executed immediately

CodePudding user response:

The building Lord give points
  • Related