Virtual base class mainly solves in multiple inheritance, the base class may be inherited multiple times, the virtual base class mainly provides a base class to the derived class, such as: #include <iostream> using namespace std;
Class base//is declared as base class Base {int nv;//default to private member public://external interface Base (int n) {NV = n;
cout << "Member of Base" << Endl;
}//base class constructor void Fun () {cout << ' fun of Base ' << Endl;
}
}; Class B1:virtual public Base {int nv1; public:b1 (int a): base (a) {cout << "Member of B1" << en
dl
}
}; Class B2:virtual public Base {int nv2; public:b2 (int a): base (a) {cout << "Member of B2" << end
L
}
}; Class D1:p ublic B1, public B2 {int NVD; public:d1 (int a): Base (a), B1 (a), B2 (a) {cout << "Member of
D1 "<< Endl;
The call to the virtual base class constructor must be listed in the member initialization list of the constructor for the}//derived class, and//if not listed, the default constructor for the virtual base class is used.
VOID Fund () {cout << "fun of D1" << Endl;
}
};
int main (void) {D1 D1 (1);
D1.fund ();
D1.fun ();
return 0; }//Here D1 inherits on B1,B2, the member variables that inherit BASE,D1 indirectly are NV, NV1, Nv2, and inherit only once,//If not inherited by the virtual base class, thatNV will be D1 from B1 and B2 each inheritance, resulting in redundancy.
Use note editing(1) A class can be used both as a virtual base class and as a non-virtual base class in a class family. (2) In the object of a derived class, a virtual base class with the same name produces only one virtual base class sub-object, and a non-virtual base class produces its own child object. (3) The virtual base class sub-object is initialized by the constructor of the furthest derived class by calling the virtual base class's constructor. (4) The farthest derived class refers to the class that is specified when an object is created in an inheritance structure. (5) A call to the virtual base class constructor must be listed in the member initialization list of the constructor for the derived class, or the default constructor for the virtual base class if it is not listed. (6) A call to a virtual base class constructor is listed in the member initialization list of a constructor in a derived class that derives directly or indirectly from a virtual base class. However, the constructor of the virtual base class is called only by the constructor of the furthest derived class that establishes the object, and the call to the virtual base class's constructor listed in all base classes of the derived class is ignored in execution, guaranteeing that the virtual base class sub-object is initialized only once. (7) When a call to a virtual base class and a non-virtual base class constructor occurs at the same time in a member initialization list, the constructor of the virtual base class is executed before the constructor of the non-virtual base class.