C ++ function overloading and virtual functions

Source: Internet
Author: User

C ++ function overloading and virtual functions

This afternoon I wrote two articles on function overloading and virtual functions in C ++. It's just a draft handout, so many terms are casual.

Function overload
How to reload functions:
What -- what is a function overload?
Why -- why should I use function overloading without function overloading?
How -- example how to use function Overloading
**************************************** ***************************************
Making names easy to use is an important feature of any programming language.
When we create an object (a variable), we need to get a name for this bucket. A function is the name of an operation. It is by describing various names in the system that we can write programs that are easy to understand and modify. Like writing an article, the goal is to communicate with readers. This raises the question of how to map the nuances of human natural language to programming languages.
Generally, a word in a natural language can represent many different meanings, which must be determined by context. This is the so-called multi-Definition of a word. From the programming point of view, the word is overloaded. The so-called heavy load means re-loading from the meaning of words. As the saying goes, it means "Changing soup without changing changes ". It is very useful to learn to understand this, especially for nuances. Example:
We can say "drink cola, drink ". It would be silly to say "Drink (drink Cola) cola, drink (drink) Wine, it is as if an obedient person has no ability to distinguish a specified action. It's not just about putting the liquid into your body. As for how to drink it, what kind of reaction will happen after drinking it.
However, most programming languages require that we set a unique identifier for each function. If we want to print three different types of data: integer, complex, and real, we usually have to use three different function names, such as p r I n t _ I n t () p r I n t _ c h a R () and p r I n t _ f l o a T (), which increase the programming workload, it also makes it difficult for readers to understand the program. For example, there are three dishes on your table. You must use golden chopsticks for the first dish, silver chopsticks for the second dish, and ivory chopsticks for the third dish, it's not the same to use chopsticks.
To put it bluntly, the handy chopsticks are an example of function overloading.
In C ++, there is another reason to overload the function name: constructor. Because the name of the constructor is determined by the class name in advance, only one constructor name is allowed. But what if we want to use several methods to create an object? For example, to create a class, it can be initialized using the standard method, or it can read information from the file for initialization. We need two constructors, one with no parameters (the default constructor ), the other string is used as a parameter to indicate the name of the file used to initialize the object. (Example: two pairs of chopsticks are convenient. One pair is from the new one, and the other is from the high temperature! But they are all convenient chopsticks .) Therefore, the essence of function Overloading is to allow functions with the same name. In this case, the constructor is called with different parameter types.
Overload is not only required for constructors, but also convenient for other functions, including non-member functions.
In addition, function overloading means that we have two libraries, both of which have a function with the same name, so long as their parameters are different, there will be no conflict.
The topic I am talking about here is not function overload, but how to make it easy for everyone to use chopsticks (function name) to get the "delicious food" on the dining table (call the function )!
Function overloading allows multiple functions with the same name (like chopsticks in multiple forms), but there is another way to make function calling more convenient. What should we do if we want to call the same function in different ways (like chopsticks in many different ways, left hand and right hand? When a function has a long list of parameters, and most parameters are called the same time, writing such a function call will get bored and the program is not readable. A common practice in C ++ is the default parameter. The default parameter is a parameter that is inserted by the compiler when the user does not specify a parameter value when calling a function. (Like eating a meal, throwing a chopsticks bowl, and not wanting to wash chopsticks, let your parents wash them .)
In this way, F ("h e l o"), F ("h I", 1) and F ("h o w D Y", 2, 'C ') it can be used to call the same function. They may also call three overloaded functions, but when the parameter list is the same, we usually want to call the same function to complete the same operation.
More in-depth descriptions of function overloading (compiler)
Void print (char );
Void print (float );
It doesn't matter whether these two functions are member functions of a class or global functions. If the compiler only uses the range of the function name, the compiler cannot generate a single internal identifier. In both cases, it must end with _ p r I n t. (Just like a pair of handy chopsticks, we don't know what food he has .)
Although the overload functions allow us to have functions with the same name, the parameter lists of these functions should be different. Therefore, to make the overload function work correctly, the compiler uses the function name to distinguish the parameter type name. The two functions defined in the global scope above, an internal name similar to _ p r I n t _ c h a R and _ p r I n t _ f l o a T may be generated. (You can see that he has a dish)
It is meaningless to define a uniform standard for such name decomposition, so different compilers may generate different internal names.
The differences between a overloaded function and a function with polymorphism (that is, a virtual function) are: calling the correct entity of the overloaded function is determined during compilation; for functions with polymorphism, the function entity we want to call is called through dynamic binding during the runtime. Polymorphism is achieved through redefinition (or rewriting. Do not be confused by overloading and overriding. The overload occurs when two or more functions have the same name. You can distinguish them by checking the number or type of their parameters.

Virtual Functions
What is a virtual function ???
A virtual function is a member function that you want to overload in a class. When you use a base class pointer or reference to point to an inherited class object, you call a virtual function, the actual version of the inherited class is called.
-- From msdn
What is polymorphism ???
Polymorphism is one of the main differences between object-oriented programming and process-oriented programming. What is polymorphism? As the saying goes: "The child is different, the child is different." polymorphism is the same processing method that can be used to deal with different situations.
Here we mainly discuss the format and conditions of virtual functions (what kind of functions are called virtual functions) and precautions for calling virtual functions.
Virtual functions are member functions and non-static member functions. The methods for describing virtual functions are as follows:
Virtual <type specifier> <Function Name> (<parameter table>)
Among them, functions described by the keyword virtual are called virtual functions.
If a member function in a class is described as a virtual function, this means that the member function may have different implementations in the derived class. (For example, a common saying is "deaf ears-decoration". It is like a person with a disability. He may not hear it, but it does not mean that his son cannot hear it, we generally call the base class "parent class" and the derived class "subclass ". But we can't say "The Dragon is born with the wind, the mouse is born with holes! His father's ears are furnishings, but here he is the organ for receiving information .)
(1) There are the same number of parameters as the virtual functions of the base class;
(2) The parameter type is the same as that of the virtual function of the base class;
(3) the return value is the same as that of the base-class virtual function, or both return pointers or references, in addition, the pointer returned by the derived class virtual function or the referenced base type is the pointer returned by the replaced virtual function in the base class or the referenced base type child type. (Just like his old man is illiterate, but he can ask his college son to show him emails and read newspapers)
Generally, after the virtual function is described in the base class, the virtual function described in the derived class should have the same number of parameters as the virtual function in the base class, and the corresponding parameter type should be the same. If not, the type of the virtual function parameter in the derived class is forcibly converted to the parameter type of the virtual function in the base class.
Abstract class
Classes with pure virtual functions are called abstract classes. An abstract class is a special class established for the purpose of abstraction and design. It is at the upper layer of the hierarchy of inheritance. Abstract classes cannot define objects. In practice, to emphasize that a class is an abstract class, you can describe the constructor of this class as a protected access control permission.
The main function of an abstract class is to organize the relevant organizations in an inheritance hierarchy to provide them with a public root. The related subclass is derived from this root. (For example, a cell phone mold)
Abstract classes depict the General Semantics of the Operation interfaces of a group of child classes. These semantics are also passed to child classes. In general, an abstract class only describes the operation interfaces of this group of sub-classes, and the complete implementation is left to the sub-classes.
An abstract class can only be used as a base class. The implementation of its pure virtual function is provided by the derived class. If the derived class does not redefine the pure virtual function, and the derived class only inherits the pure virtual function of the base class, the derived class is still an abstract class. If the implementation of the basic class pure virtual function is provided in the derived class, the derived class is no longer an abstract class. It is a concrete class that can create objects.
One instance:
Class person ()
{Public:
//......
Void ()
{People eat;
}
//......
Char * Name;
Int age;
};
Class dog ()
{Public:
//......
Void ()
{Dog shit;
}
//......
Char * Name;
Int age;
};
Humans and dogs have some similar things, such as names, ages, eating actions, etc. Some people think that for code reuse, humans can inherit the Dog class, however, the idea of data redundancy is doomed, so some people come up with another idea to define a class like this:
In this category, there are some things that humans and dogs share, such as age, name, weight, and so on, but they do not exist, it is only used to derive other classes, such as humans and dogs, so that the system can be cleaned up ,..... , There are many benefits.
In this world, there is no such thing as between humans and dogs. Therefore, it is meaningless to "eat" in "between human and dogs, it is also difficult for you to define the content of it, and it is not necessary, so it is defined as a pure virtual function in the form of: Virtual void eat () = 0; used to tell the system:
1. This function can have no function definition;
2. The class that owns this function is an abstract class;
You may say that pure virtual functions are meaningless. Why do you need them? What is their role?
Prepare for the implementation of polymorphism !!!

Functions of virtual functions:
One: the same type
2. Always
3: Use it if there is, and use it if there is no such thing
Separate explanation of the ambiguity:
What is ambiguity? Literally, it is the ambiguity. Why does it happen? Here is an example: for example, if you go to the store to buy cigarettes, they are all Yellow Crane Tower, with, 24, and 18 prices, all of which are smoke, that is, smoke is their base class, which package do you want to buy? Tell the boss: "Take the bag, Yellow Crane Tower !" Who knows how much smoke you have bought? Here we have the ambiguity! At the same time, it also introduces a solution to the ambiguity! The boss will ask you, "How much is a pack !" Here you can make a choice! However, the compiler will not ask you which parent class member function to call! So you need to explain it in advance! (Y: Gety ())

Summary:
To sum up with an example, function Overloading is a static polymorphism (static Association). You can imagine that you go to a restaurant to eat different dishes (different quantities, different types of parameters), using the same pair of chopsticks (function name), do it yourself, do not instruct others to help you implement the function (do it yourself, remember enough food ). Virtual functions are dynamic polymorphism (Dynamic Association), and you can imagine that you are either an elderly man or a rich seller at a restaurant to have a big meal, don't do it yourself, and eat very well. Different foods should use different tableware (different objects), and call others (sub-class member function implementation function) to feed you. You just need to instruct (base class pointer or reference pointing) to it. In the eyes of others, you are also eating (with corresponding functions), but you are not doing it at all, it is all done by your younger brother (subclass member function implementation ).

Related 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.