First, let’s introduce our new knowledge point— virtual function .
What kind of function is this? To put it simply, it is a function declared with virtual in front of a function. The general form is as follows:
virtual function return value function name (formal parameter) {function body}
So what is it used for? The emergence of virtual functions allows the connection between the function and the function body to be established at runtime, which is the so-called dynamic binding . Then when the derived class of the virtual function is running, the effect of executing the same method but with different results can be achieved according to dynamic binding at runtime, which is the so-called polymorphism. In this way, there is a way to solve the problem in the previous section.
Next, we only need to declare the area method in the base class as a virtual function, and then any pointer or reference of type Point in the main function can be called boldly, and there is no need to worry about type issues. Because they will decide whose method to call based on the actual object type to achieve dynamic binding.
The code is as follows:
/************************************//Des: C++ tutorial demo//Author: Huang//Copyright:www.dotcpp.com//Date:2017/12/20************************************ *******/#include<iostream>usingnamespacestd;#definePI3.1415926classPoint{private:intx,y;public:Point(intx=0,inty=0){this->x=x;this->y =y;}virtualdoublearea(){return0.0;}};classCircle:publicPoint{private:intr;public:Circle(intx,inty,intR):Point(x,y){r=R;}doublearea(){ returnPI*r*r;}};intmain(){PointA(10,10);cout<<A.area()<<endl;CircleB(10,10,20);cout<<B.area()< <endl;Point*p;p=&B;cout<<p->area()<<endl;Point&pp=B;cout<<pp.area()<<endl;return0;}
After modification, compile and run as follows:
Please experiment on your own computer to experience the role of virtual functions and polymorphism.
Things to note are:
1. Virtual functions cannot be static member functions or friend functions because they do not belong to an object.
2. Inline functions cannot dynamically determine their location during runtime. Even if the virtual function is defined inside the class, it will still be regarded as non-inline during compilation.
3. The constructor cannot be a virtual function, and the destructor can be a virtual function, and is usually declared as a virtual function.