1#include <iostream>2 using namespacestd;3 classbase{4 Public:5 Base ()6 {7A=5;8cout<<"Base a="<<a<<Endl;9 }Ten protected: One intA//If this is a private variable, then no access is granted in all of his derived classes A //derived classes can only access the public and protected members of the base class directly - //Private members are limited to their own use only. - //protected members allow derived classes to be used without allowing direct invocation through objects the //The public class is allowed for all calls - }; - classBASE1:Virtual Publicbase{ - Public: + intB1; - Base1 () + { Aa=a+Ten; atcout<<"Base1 a="<<a<<Endl; - } - }; - classBASE2:Virtual Publicbase{ - Public: - intB2; in Base2 () - { toa=a+ -; +cout<<"Base2 a="<<a<<Endl; - } the }; * classDerived: PublicBASE1, Publicbase2{ $ Public:Panax Notoginseng intD; - Derived () the { +cout<<"base1::a="<<Base1::a<<Endl; Acout<<"base2::a="<<Base2::a<<Endl; the } + }; - //defining a virtual base class is replicated only once for the same base class. $ //from the execution of this example function, it is shown that: $ //created by the derived class, causes the creation of the Base1 class, and then the creation of Base2 - //to create a Base1 class, you must first create his derived class base - //The base class is created and then Base1 created, and then the base class is called once the //The Base1 class is created before the BASE2 is created. - //because it is a virtual inheritance, base has been called once, and it no longer calls the base classWuyi //Base2 uses the value of the base class that is invoked on the basis of the Base1 creation. the //after all the base classes are created sequentially, then create the bottommost derived class derived - intMain () Wu { - Derived obj; About return 0; $ } - /* - result of execution at virtual inheritance - Base a=5 A Base1 a=15 + Base2 a=35 the base1::a=35 - base2::a=35 $ */ the /* the results performed on non-virtual inheritance the Base a=5 the Base1 a=15 - Base a=5 in Base2 a=25 the base1::a=15 the base2::a=25 About */
Understanding of C + + derived class inheritance