Virtual functions and polymorphism of C + +

Source: Internet
Author: User
Tags function prototype

More dry goods-need to ponder their own understanding:

C + + supports two types of polymorphism:
1. Compile-time polymorphism (static binding-early binding)
Polymorphism that can be identified during the program compilation phase
implemented by using overloaded mechanisms (overloaded functions)

(template) http://blog.csdn.net/my_business/article/details/12194691

2. Run-time polymorphism (dynamic binding-late binding)
You must wait until the program runs to determine the polymorphism
To implement by using virtual functions

http://blog.csdn.net/zp752963831/article/details/46635885

In the first parent class, a function is defined as a virtual function, and in his subclass it is a virtual function whether or not to add virtual.

Example:

classbase{ Public:Virtual voidFuninti) {OutputDebugString (_t ("base::fun (int i)"));}};classBasea: Publicbase{ Public:Virtual voidFuninti) {OutputDebugString (_t ("basea::fun (int i)"));}};
View Code

The baseb of the fun function plus and no virtual function is irrelevant, it is a virtual function

But if he continues to be a base class and uses polymorphism, it should add a virtual

Access permissions for virtual functions:
Access to a virtual function defined in a derived class does not affect the late binding to it
(That is, only public,private or protect defined in the first parent class have control over the access to the virtual function)

Late binding and instantiation of the object's access rights to functions in class

class Base{ Public:    Base(): Strbase (_t ("Base") ) {log (); } Virtualvoidlog () {MessageBox (:: Gettopwindow (NULL), _t ("Base"), _t ("Base"), MB_OK); } Public: param strbase; Param*pStr;};classChild: Public Base{ Public: Child () {}/*Child (const child& Other) {pStr = new param (_t ("child2")); }*/
Pritave:
Virtual voidlog () {MessageBox (:: Gettopwindow (NULL), _t (" Child"), _t (" Child"), MB_OK); } Public: };
int main ()
{
Base * pbase = new Child ();
Pbase->log ();//ok
child* pchild = static_cast<child*> pbase;
Pchild->log ();//error
}

To call a virtual function in a member function:
In a virtual or non-virtual member function of a base class or derived class, you can directly adjust the
Using virtual or non-virtual functions of the class system

class Base{ Public:    Base() {log (); }        voidGo () {log (); }    Virtual voidlog () {MessageBox (:: Gettopwindow (NULL), _t ("Base"), _t ("Base"), MB_OK); }};classChild: Public Base{ Public: Child () {}voidGo () {log (); }Private:    Virtual voidlog () {MessageBox (:: Gettopwindow (NULL), _t (" Child"), _t (" Child"), MB_OK); } Public:};intMain () {Base* PBase =NewChild (); PBase->go ();//OK calls the parent class's go, inside calls the subclass's log function. child* pchild = static_cast<child*>(pbase); Pchild->go ();//go inside directly call your own}

To call a virtual function in a construct/destructor:
When a virtual function is called in a constructor or destructor, an early binding is used.
That is, the virtual function mechanism does not work in the constructor.

class Base{ Public:    Base() {log (); }    voidGo () {log (); }    Virtual voidlog () {MessageBox (:: Gettopwindow (NULL), _t ("Base"), _t ("Base"), MB_OK); }};classChild: Public Base{ Public: Child () {log (); }    voidGo () {log (); }Private:    Virtual voidlog () {MessageBox (:: Gettopwindow (NULL), _t (" Child"), _t (" Child"), MB_OK); }};intMain () {Base* PBase =NewChild ();//when the parent class is constructed, the parent class constructs a call to its own//Log, subclass construct, then use the subclass's log function. }

Virtual functions and Default arguments:
The function being run is a derived function, but the default argument used is the default argument in the parent class
That is: The default argument of the virtual function does not support late binding.

class Base{ Public:    Base()    {    }    Virtual voidLogintParami =1) {sstringt str=Parami;    OutputDebugString (str); }};classChild: Public Base{ Public: Child () {}Virtual voidLogintParami =2) {sstringt str=Parami;    OutputDebugString (str); }};intMain () {Base* PBase =NewChild (); PBase->log ();//Output 1child* pchild = static_cast<child*>(pbase); Pchild->log ();//Output 2}

Pure virtual function:
Definition: A pure virtual function is a virtual function declared in a base class that is not defined in the base class, but requires that any derived class define its own implementation method.
The method of implementing a pure virtual function in a base class is to add "=0" after the function prototype: virtual void Funtion1 () =0
* Reasons for Introduction:
1) in order to facilitate the use of polymorphic features, we often need to define virtual functions in the base class.
2) In many cases, the base class itself generates objects that are unreasonable.

3) Implement Interface

The concept of pure virtual functions is introduced and functions are defined as pure virtual functions (method: Virtual ReturnType function () = 0;), the compiler will
Must be overloaded in a derived class to achieve polymorphism. A class that contains a purely virtual function is called an abstract class, and it cannot produce an object.

1  

Covered:
In C + +, derived classes inherit all the characteristics of a base class, but sometimes to more accurately describe an object in the objective world, an interface function inherited from the base class needs to be modified:
This can be done by defining a function in the derived class with the same name as the base class, and the return value, the parameter type, or the order or number of functions that can be different.
Thus, when a function of the same type is called through a derived class object, the function defined in the derived class is called. Other words
Derived classes modify the interface behavior inherited from a base class, or a function that is called a derived class overrides a function of the same name in the base class.


Overloading: Overloaded class member functions are somewhat similar to overrides: the same method (function name) accomplishes different behavior


The difference between overriding and overloading:
1. Overloading is the same name as the overloaded function, and the parameters are different (type, order, or quantity, at least one of the three), and the return value can be different from another function.
2. Overloaded functions must be in the same class or between ordinary functions that are not members of a class, and cannot be distributed between base classes and derived classes.
3. Overwrite is the case where the base class has the same name as the identifier that appears in the derived class.

Note:
1. Virtual function is a special set of covering functions, which requires the same function name, return value, parameter type, quantity, and order in the same set of virtual functions.
When a virtual function is called through the object name, the same as the rule that calls the Override function-----early binding.
When a virtual function is called by a pointer or reference to an object, it is called a virtual function that is defined in the class that the pointer actually points to or that corresponds to the object that is actually referenced.

2. If there are two functions of the same name outside of the class, or if two members of the same name have the same parameters, but the return values are different, the compiler does not consider overloading and considers them to be ambiguous and gives an error.
3. If in a set of virtual functions, two virtual functions return only different values, but the parameters and names are the same, the compiler also considers the error.

Three comparison tables:

*=======================================================================================*
| function name | return value | parameter | binding TIME | Scope of Application |
*---------------+---------------+---------------+-----------------------+---------------*
| virtual function | same | | Late binding (pointer/reference call) | base class and Derivation |
|||| Early binding (object name invocation) | between Classes |
*---------------+---------------+---------------+-----------------------+---------------*
| overloaded functions | can be different | must be different | early bound | out-of-class functions or the same |
||||| Functions in a Class |
*---------------+---------------+---------------+-----------------------+---------------*
| overlay Function | can be different | can be different | Early bound (dominant rule) | base class and derived class |
||||| Between |
*=======================================================================================*

Virtual functions and polymorphism of C + +

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.