Virtual functions (C ++ virtual functions) in C ++ practical generic programming
A Discussion on C ++ virtual functions
During programming, we often encounter this situation. Suppose there are two objects, and you need to call their OnDraw methods in the function separately. Our previous approach is generally like this.
Void f (int iType)
{
Switch (iType)
{
Case 1:
// CCircle OnDraw
Break;
Case 2:
// CRectangle OnDraw
Break;
}
}
This method can certainly solve our problem, but if there is a new type to be added, it must add code to it, so that the code in the function will be longer and longer. You may think that I don't have many types, and it won't be too long to add them down, but this idea is not advisable, because in actual work, we often encounter the situation that, A system may have to be maintained for several years or even 10 years, so there are a lot of unpredictable things, so there is no such luck in design. C ++ provides virtual functions to help us solve this problem.
Class CShape
{
Public:
Virtual void OnDraw (){}
};
Class CCircle: public CShape
{
Public:
Void OnDraw ()
{
Cout <"CCircle OnDraw" <
}
};
Class CRectangle: public CShape
{
Void OnDraw ()
{
Cout <"CRectangle OnDraw" <
}
};
Define an interface function and use the base class as the type parameter. After the object is passed in, the corresponding function can be called.
Void SelfDraw (CShape * _ shap)
{
_ Shap-> OnDraw ();
}
You only need to write code similar to the following when calling.
CCircle c1;
CRectangle r1;
SelfDraw (& c1 );
SelfDraw (& r1 );
The result after the program is compiled and run is as follows.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + release/ydLU1eLR + release/K/aOsxMfDtMjDztLDx8C0v7S/release + IDxpbWcgc3JjPQ = "" alt = "\">
The secret is _ vfptr (virtual function pointer) __vfptr is a pointer array pointing to a virtual function. When a CCircle object passes in a base class pointer, the virtual function pointer points to the OnDraw function of the CCircle overload, so we can see that _ shap-> OnDraw () in SelfDraw can call the corresponding subclass function correctly.