Boiling polymorphism-Image Interpretation of C ++ Polymorphism

Source: Internet
Author: User

What is the shape of water?

At first glance, it seems that this question is very unreasonable. In fact, think carefully, water is the perfect embodiment of "polymorphism" in nature. No? Use a cylindrical container to hold water, then water is cylindrical; replace it with a conical container, water will become a conical. In this process, we do not need to care about how water changes its shape, nor do we need to care about what water has done in the process of changing its shape, it is enough to provide it with a container of any shape.

The so-called polymorphism in OO (Object Oriented) is also true. For a method with the same name (Water), we call it in different situations (Container), so the behavior it completes (Where_Am_ I) is also different. Here I will explain several different implementations of "polymorphism" in C ++.

 

Function Overload)

 

Here is a very simple function max, which returns the larger of the two input parameters.

Int max (int a, int B)

{

If (a> B)

Return;

Else

Return B;

}

I believe that the specific content of this Code does not need to be explained. Yes, this is a very basic code. You may find that this max function only applies to parameters of the int type. So what if I still need a max for the double type?

Fortunately, the C ++ language itself provides this function, which allows us to use the same name when defining a function-it is a function overload. That is to say, we can continue to define a double version of max:

Double max (double a, double B)

{

If (a> B)

Return;

Else

Return B;

}

Then, call the two functions in our code:

Void f (void)

{

Int a = max (1, 2 );

Double B = max (1.5, 2.5 );

}

In this way, we do not need to care which version of max is called. The Compiler automatically selects the most appropriate max function for calling Based on the given parameter type (int or double.

 

Template)

 

Function overloading does provide us with great convenience. We don't need to worry about which function to call. The Compiler selects the most appropriate function to call based on the given parameter type. However, in the following cases, the function overload is not very suitable:

The Code content of the function body is basically the same.

You need to write functions of the same function for multiple types.

That is to say, we may need more versions of max (int, double, or even more custom types, such as the complex), but all their code is:

If (a> B)

Return;

Else

Return B;

In this way, what we need to do is more inclined to be physical labor. In addition, too many repetitive jobs will inevitably lead to the hidden danger of errors. In this regard, C ++ provides us with a solution, that is, a template. For the max functions of the above versions with the same content, we only need to provide a function template like the following:

Template <typename T>

T max (const T & a, const T & B)

{

If (a> B)

Return;

Else

Return B;

}

Template is the keyword of C ++, indicating that the code block below it will use the template. The content in the angle brackets is called a template parameter, indicating that T will be used as a definite type in the following code template. The const reference is used for parameters to avoid unnecessary overhead for passing values when class objects are encountered. After the template is defined, we can use it like this:

Void f (void)

{

Int a = max <int> (1, 2 );

Double B = max <double> (1.5, 2.5 );

}

For this code, the compiler will respectively fill int and double to the T location in the function template, that is, max <int> and max <double> Generate an object code for the max function respectively. In this way, it achieves the same effect as function overload, but the workload of programmers is not the same as that of the day.

 

Virtual Functions)

 

The following uses water as an example to describe the polymorphism forms provided by virtual functions. First, we create a Water class to represent Water.

Class Water

{

Public:

Virtual void Where_Am_ I () = 0;

};

Just as it makes no sense to discuss the shape of Water separately, we certainly cannot allow instantiation of the Water class here, so the member function Where_Am_ I is defined as a pure virtual function. Below, we will define three different conditions of Water in Bottle, Glass, and Lake respectively:

Class Water_In_Bottle: public Water

{

Public:

Virtual void Where_Am_ I ()

{

Cout <"Now I'm in a bottle." <endl;

}

};

 

Class Water_In_Glass: public Water

{

Public:

Virtual void Where_Am_ I ()

{

Cout <"Now I'm in a glass." <endl;

}

};

 

Class Water_In_Lake: public Water

{

Public:

Virtual void Where_Am_ I ()

{

Cout <"Now I'm in a lake." <endl;

}

};

The three functions implement the member function Where_Am_ I. Then, the implementation of polymorphism can be completed through a pointer to Water:

Void f (void)

{

Water_In_Bottle;

Water_In_Glass B;

Water_In_Lake c;

 

Water * pWater [3];

PWater [0] = &;

PWater [1] = & B;

PWater [2] = & c;

 

For (int I = 0; I <3; I ++)

{

PWater [I]-> Where_Am_ I ();

}

}

In this way, the program runs as follows:

Now I'm in a bottle.

Now I'm in a glass.

Now I'm in a lake.

Well, as you can see, we don't need to worry about which kind of water pWater points to, but just need to use this pointer for the same call, water itself can choose the corresponding behavior based on its own location. The polymorphism of virtual functions is very useful, especially when using C ++ for Windows programming. Considering that different windows can make different responses to the same user behavior, it is precisely because the specific implementation of the corresponding message response virtual function is different that this effect can be achieved.

Boiling polymorphism, temporarily boiled here. What we talk about here is only the expression of C ++ for polymorphism, but not the three technologies in this article (heavy load, template, virtual function) the specific content is explained too much-after all, some technical details will inevitably be investigated for a long time, for example, parameter matching will inevitably be mentioned when heavy load occurs, when it comes to templates, it is inevitable to hook up with generics. When it comes to virtual functions, we can't help but mention VTable ...... I am free of charge here, because my goal is to let the readers have a perceptual understanding of the polymorphism of OO through the simple examples above. Thank you for reading this article.

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.