Reference [link]
https://www.cnblogs.com/weiyouqing/p/7544988.html
What is a virtual function:
Virtual function is a member function of a class that you want to override when you use a base class pointer or reference point to a derived class object, when you call a virtual function call is the actual version of class inheritance. - Excerpt from MSDN
The most critical feature of the virtual function is "dynamic binding", which can be a pointer to the object is determined at run time and automatically calling the corresponding function.
Be sure to note the difference between "static binding" and "dynamic binding," the.
【Reference Code】
#include <iostream>
//#include <conio.h> //getch() isn't a standard lib function
//#include <curses.h> //g++ virtual.cpp -lncurses -std=c++11
#include <stdio.h>
using namespace std;
the Parent class
{
public:
char Data [20 is];
void The Function1 () {the printf ( "This IS parent, function1 \ n-");}
Virtual void Function2 (); // this is a virtual function declared Function2
} parent;
void Parent::Function2(){
printf("This is parent,function2\n");
}
class Child:public Parent
{
void Function1() { printf("This is child,function1\n"); }
void Function2();
}child;
void Child::Function2() {
printf("This is child,function2\n");
}
typedef Parent* pParent;
main int (int argc, char * the argv [])
{
pParent P1; // define a base pointer
char ch[] = "hello world";
printf("%s\n", ch);
if (getchar () == 'c ') // If you enter a lowercase letter C
P1 = & Child; // points to the object class inherits
the else
P1 = & parent; // otherwise to base class object
p1-> Function1 (); // here at compile time will be given directly Parent :: Function1 () entry address.
p1-> Function2 (); // Note that, the execution of which is the Function2
return 0;
}