Virtual functions automatically inherit, regardless of how many times the inheritance has passed, and the derived class retains the virtual attribute.
If the subclass does not overwrite the virtual function in the parent class, but instead overloads it, the virtual function in the subclass holds the virtual function of the child class and the parent class, but although it is the same name, the virtual function of the parent class is placed in front, so the virtual function of the parent class is called first, thereby losing the virtual attribute.
Class Base
{
Public
Base () {func1 ();}
virtual void func1 ()
{
cout<< "Base1111111111111111" <<endl;
}
virtual void Func2 ()
{
cout<< "Base2222222222222222222" <<endl;
}
~base () {Func2 ();}
};
Class Sub:public Base
{
Public
Sub () {func1 ();}
virtual void func1 ()
{
cout<< "Sub11111111111111111" <<endl;
}
virtual void Func2 ()
{
cout<< "Sub222222222222222222" <<endl;
}
~sub () {Func2 ();}
};
int _tmain (int argc, _tchar* argv[])
{
Sub Sub;
System ("pause");
return 0;
}
Before you create a subclass, you must first create a parent class. The constructor of the parent class is first out and then the subclass. Some books say that this is a subclass of static-linked, it must be wrong. Instead, if there are no constructors and destructors in the subclass, they cannot be displayed. So the function is called by the parent class.
3. Virtual destructor
Class Base
{
Public
Base () {func1 ();}
void Func1 ()
{
cout<< "Base1111111111111111" <<endl;
}
void Func2 ()
{
cout<< "Base2222222222222222222" <<endl;
}
~base () {Func2 ();}
};
Class Sub:public Base
{
Public
Sub () {func1 ();}
void Func1 ()
{
cout<< "Sub11111111111111111" <<endl;
}
void Func2 ()
{
cout<< "Sub222222222222222222" <<endl;
}
~sub () {Func2 ();}
};
int _tmain (int argc, _tchar* argv[])
{
base* base = new Sub;
Delete base;
System ("pause");
return 0;
}
The destructor of the subclass is not called, and if the destructor of the parent class becomes virtual, it is destroyed together.
The reason is that the virtual function table in the subclass is assigned to the parent class, and delete base is actually the destructor of the called subclass, plus the parent class is naturally refactored if the subclass is refactored (the compiler silently adds a call to the parent class destructor to the child class's destructor ).
This article from "Very blog" blog, reproduced please contact the author!
Some features of the virtual function of the advanced path of C + + 03