The polymorphism of C + + language is related to the virtual function of C + + class
Introduce a problem: Define a pointer to a base class, point to a derived class object, and then invoke the corresponding method based on the pointer, what effect does it have?
Class CBase
{
Public
virtual void Vfun ()
{
cout<< "Vfun from base class" <<endl;
}
void Fun ()
{
cout<< "Fun from base class" <<endl;
}
};
Class Cderive:public CBase
{
Public
virtual void Vfun ()
{
cout<< "Vfun from derive class" <<endl;
}
void Fun ()
{
cout<< "Fun from derive class" <<endl;
}
};
Cbase* pbase;
CBase Base;
Cderive derive;
"1" If PBase = &derive;
Pbase->vfun ();
Pbase->fun ();
Output results
Vfun from derive class
Fun from derive class
Virtual functions are overloaded in derived classes and pointers point to derived class objects
"2" If pbase is only defined, but not initialized;
Pbase->vfun ();
Pbase->fun ();
Outputs the corresponding function in the base class to process the result
To call a base class pointer to a function method of a derived class, either let PBase point to the derived class object, or type display cast (cderive*) pbase for pbase;
(cderive*) Pbase->vfun ();
(cderive*) Pbase->fun ();
For each class that has a virtual function inside it, the compiler generates a virtual function table for it (vtable), and each element in the table points to the address of a virtual function, and the compiler generates a member variable-----the virtual function table pointer (VPTR) to the virtual function table, which is inherited ...
[00000]-[2015-06-22]-[00]-[c++ virtual function]