You can let member function operations generalize, with pointers to the base class pointing to objects of different derived classes,
When a base-class pointer calls its virtual member function, it calls the member function that actually points to the object.
Instead of the member function defined in the base class (as long as the derived class overrides the member function).
If it is not a virtual function, the call will be called regardless of which derived class object The base class pointer is pointing to.
The function defined in the base class is called.
Program 1:
#i nclude <iostream>
Using Namecpace std;
Class B0//base class B0 declaration
{public:
void display () {cout<< "B0::d isplay ()" <<ENDL;}//Public member function
};
Class B1:public B0
{
Public
void display () {cout<< "B1::d isplay ()" <<ENDL;}
};
Class D1:public B1
{
Public
void display () {cout<< "D1::d isplay ()" <<ENDL;}
};
void Fun (B0 *ptr)
{Ptr->display ();//"Object pointer, member name"}
void main ()//main function
{B0 B0;//Declare B0 class object
B1 B1; Declaring a B1 class object
D1 D1; Declaring a D1 class object
B0 *p; Declaring a B0 class pointer
p=&b0; B0 class pointer to B0 class object
Fun (p);
p=&b1; B0 class pointer to B1 class object
Fun (p);
p=&d1; B0 class pointer to D1 class object
Fun (p);
}
Operation Result:
B0::d isplay ()
B0::d isplay ()
B0::d isplay ()
Program 2:
#i nclude <iostream>
using namespace Std;
Class B0//base class B0 declaration
{public://external interface
virtual void display ()//virtual member function
{cout<< "B0::d isplay ()" <<ENDL;}
};
Class B1:public B0//Public derivative
{public:
void display () {cout<< "B1::d isplay ()" <<endl; }
};
Class D1:public B1//Public derivative
{public:
void display () {cout<< "D1::d isplay ()" <<endl; }
};
void Fun (B0 *ptr)//Normal function
{Ptr->display (); }
void main ()//main function
{B0 B0, *p;//Declare base class objects and pointers
B1 B1; Declaring derived class objects
D1 D1; Declaring derived class objects
p=&b0;
Fun (p); Call the base class B0 function member
p=&b1;
Fun (p); Calling a derived class B1 function member
p=&d1;
Fun (p); Calling a derived class D1 function member
}
Operation Result:
B0::d isplay ()
B1::d isplay ()
D1::d isplay ()
Virtual functions are the basis of dynamic binding.
A non-static member function.
In the declaration of the class, write virtual before the function prototype.
Virtual is used only to describe prototypes in a class declaration and cannot be used when a function is implemented.
is inherited, a virtual function is declared in the base class, and the same prototype function is automatically a virtual function, whether or not it is described in a derived class.
Essence: Overrides are not overloaded declarations.
Invocation: By a base-class pointer or reference, execution determines which function is called based on the class of the object that the pointer is pointing to.
Http://www.cnblogs.com/kyleada/archive/2011/05/19/2051184.html
The role of virtual function