C + + polymorphism and virtual functions

Source: Internet
Author: User

The polymorphism in object-oriented programming is to send the same message to different objects, and different objects produce different behaviors for the same message. In the program, the message is called the function, the different behavior refers to the different implementation method, namely executes the different function body. It can also be said that the implementation of "one interface, a variety of methods."
  
From the perspective of implementation, polymorphism can be divided into two categories: compile-time polymorphism and run-time polymorphism. The former is implemented by static linking, such as overloading of functions in C + + and overloading of operators. The latter is realized by dynamic linking, and the polymorphism in C + + is mainly realized by virtual function.


Assignment compatible

before you say virtual functions, however, you'll start by describing a copy-compatible relationship between a base class and a derived class object. It is also the basis for learning virtual functions afterwards.
We sometimes assign integer data to variables of the double type. Before assigning a value, convert the shaping data to double-precision, and assign it to the variable of the double-precision type.volume. This automatic conversion and assignment between different types of data is called assignment compatibility. Similarly, there is an assignment compatibility relationship between the base class and the derived class, which means that any place where the base class object is needed can be replaced with a public derived class object. Why only public inheritance is possible, because derived classes in public inheritance retain all members in the base class except for construction and destruction, the access rights of the base class's public or protected members are preserved as is, and the public functions of the base class can be called outside the derived class to access the private members of the base class. Therefore, the functions that the base class can implement can also be derived classes.

(1) A derived class object is assigned a value directly to the base class, the value of which is the same as the values of the data members in the base class data member and the derived class;

(2) A derived class object can initialize a base class object reference ;

(3) The address of the derived class object can be assigned to the base class object pointer ;

(4) A function parameter is a reference to a base class object or a base class object that, when called, can use the object of the derived class as an argument;


Look at the following example

#include "stdafx.h" #include <iostream> #include <string>class abcbase{private:        std::string ABC;    Public:        abcbase (std::string ABC)        {            abc=abc;        } void Showabc ();}; void Abcbase::showabc () {    std::cout<< "letter Abc=>" <<ABC<<STD::ENDL;} Class X:public Abcbase{public:        X (std::string x): Abcbase (x) {}};void function (Abcbase &base) {base.showabc ();} int main () {    abcbase base ("A"); Base.showabc ();    x x ("B"); Base=x;base.showabc ();    Abcbase &base1=x;    BASE1.SHOWABC ();    Abcbase *base2=&x;    BASE2->SHOWABC ();    function (x); return0;} </span>

the results of the operation are as follows "


It is important to note that:

First, when assigning values to base classes and derived class objects, the derived class must be public-inherited.

Second, only the derived class object is allowed to assign a value to the base class object , which in turn is not allowed;


Virtual functions

Virtual functions allow the connection between a function call and a function body to be established at run time, that is, to decide how to act at run time.

The format of the virtual function declaration:

Virtual return type function name (formal parameter list)

{

function body

}


So what's the use of defining virtual functions? Let's take a look at the following example:

#include "stdafx.h" #include <iostream> #include <string>class graph{protected:double x;double y;public: Graph (double x,double y); void Showarea ();}; Graph::graph (double x,double y) {this->x=x;this->y=y;} void Graph::showarea () {std::cout<< "calculates the plot area" &LT;&LT;STD::ENDL;} Class Rectangle:public Graph{public:rectangle (double x,double y): Graph (x, y) {};void showarea ();}; void Rectangle::showarea () {std::cout<< "rectangular area:" &LT;&LT;X*Y&LT;&LT;STD::ENDL;} Class Triangle:public Graph{public:triangle (Double d,double h): Graph (d,h) {};void showarea ();}; void Triangle::showarea () {std::cout<< "Triangle area:" &LT;&LT;X*Y*0.5&LT;&LT;STD::ENDL;} Class Circle:public Graph{public:circle (Double R): Graph (r,r) {};void showarea ();}; void Circle::showarea () {std::cout<< "circular area:" &LT;&LT;3.14*X*Y&LT;&LT;STD::ENDL;}    int main () {Graph *graph;    Rectangle Rectangle (10,5);    graph=&rectangle;    Graph->showarea ();    Triangle Triangle (5,2.4); Graph=?    Graph->showarea ();    Circle Circle (2);    graph=&circle; Graph->showarea (); return0;}

The results of the operation are as follows:


The result seems to be different from what we imagined, since the graph Class (graph Class) object graph pointer points to the rectangle class (Rectangle Class) object, the Triangle Class (triangle Class) object, and the Circle Class (Circle Class) object, Then you should execute their own corresponding member function Showarea (), how can the result be the graph Class (graph Class) object graph in the member function?

In fact, when a base-class object pointer points to an object of a public-derived class, it can access only the members inherited from the base class, not the members defined in the derived class. However, a dynamic pointer is used to express the nature of a dynamic invocation, which is the object that the current pointer points to, and the member function of that object's corresponding class is called. That is how to solve the problem, then the virtual function reflects its role. In fact, we only need to add a keyword to the Showarea () function declaration that appears in all the classes in the previous sample code, virtual:

#include "stdafx.h" #include <iostream> #include <string>class graph{protected:double x;double y;public: Graph (double x,double y); voidvirtual showarea ();//defined as virtual function or virtual void Showarea ()}; Graph::graph (double x,double y) {this->x=x;this->y=y;} void Graph::showarea () {std::cout<< "calculates the plot area" &LT;&LT;STD::ENDL;} Class Rectangle:public Graph{public:rectangle (double x,double y): Graph (x, y) {};virtualvoid showarea ();//defined as virtual function};voi D Rectangle::showarea () {std::cout<< "rectangular area:" &LT;&LT;X*Y&LT;&LT;STD::ENDL;} Class Triangle:public Graph{public:triangle (Double d,double h): Graph (d,h) {};virtualvoid showarea ();//defined as virtual function};void Triangle::showarea () {std::cout<< "Triangle area:" &LT;&LT;X*Y*0.5&LT;&LT;STD::ENDL;} Class Circle:public Graph{public:circle (Double R): Graph (r,r) {};virtualvoid showarea ();//defined as virtual function};void Circle::showa Rea () {std::cout<< "Circle area:" <<3.14*x*y<<std::endl;}    int main () {Graph *graph;    Rectangle Rectangle (10,5);graph=&rectangle;    Graph->showarea ();    Triangle Triangle (5,2.4);    Graph=?    Graph->showarea ();    Circle Circle (2);    graph=&circle; Graph->showarea (); return0;}

The rest of the code is intact, so the result of running it is what we need:


After a member function in a base class is declared as a virtual function, it can be redefined in subsequent derived classes. When defined, however, its function prototypes, including the return type, function name, number of arguments, and order of parameter types, must be identical to the prototype in the base class. In fact, in the above-mentioned modified example code, as long as the virtual function is explicitly declared in the base class, it is necessary to explicitly declare it in the subsequent derived class, which can be omitted, because the system will determine whether it is not a virtual function according to its exact same prototype as the virtual function in the base class. Therefore, virtual functions in the derived class above are not explicitly declared or virtual.

Finally, the virtual function to do some additional explanation:

(1) Because virtual functions are based on assignment compatibility, the condition that the assignment is compatible is that the derived class derives from the base class public. Therefore, using virtual functions, derived classes must be public-derived from the base class;

(2) Define the virtual function, not necessarily in the class at the highest level, but in the hierarchy of the need for dynamic polymorphism of the highest class in the declaration of the virtual function;

(3) Although in the example code above, we can also use the corresponding graphical object and dot operator to access virtual functions, such as Rectangcle.showarea (), but this call is statically linked at compile time, and it does not take full advantage of the properties of the virtual function. Only the virtual function can be accessed by the base class object to get the characteristic of dynamic Union;

(4) A virtual function is still a virtual function regardless of the number of times it is inherited by the public;

(5) A virtual function must be a member function of the same class, not a friend function, or a static member function. Because a virtual function call relies on a particular object class to determine which function to activate;

(6) An inline function cannot be a virtual function, because an inline function cannot dynamically determine its location in the run, even if the virtual function is defined inside the class, and is considered non-inline at compile time;

(7) A constructor function cannot be a virtual function, but a destructor can be a virtual function;

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + polymorphism and virtual functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.