# Include <iostream> using namespace STD; Class A {public: A () {cout <"A" <Endl ;}~ A () {} virtual void func1 () {cout <"only in a" <Endl;} virtual void func2 () {cout <"virtual in a" <Endl;} void func3 () {cout <"non virtual in a" <Endl ;}}; Class B: public A {public: B () {cout <"B" <Endl ;}~ B () {} void func2 () {cout <"virtual in B" <Endl;} void func3 () {cout <"non virtual in B" <Endl ;}; int main () {B * B = new B (); A * A = (*) b; B-> func1 (); B-> func2 (); B-> func3 (); A-> func1 (); A-> func2 (); a-> func3 (); getchar (); Return 0 ;}
Output result:
1. Before creating a subclass to call the constructor of the subclass, the constructor of the parent class is called.
2. Virtual is related to polymorphism. A function with the virtual keyword is added. When calling a function, if the subclass has one, The subclass is called first. If the subclass does not exist, the function of the parent class is called.
3. When the parent class Pointer Points to a subclass object, if the called function exists in the parent class and the subclass, but it is not a virtual function in the parent class, whether it is a virtual function in the subclass. When called using the parent class pointer, the function in the parent class is executed instead of the function in the subclass. When called using the subclass pointer, the function in the subclass is executed.