Talking about C + + polymorphism

Source: Internet
Author: User
Tags function prototype

        C + + Programming language is a widely used computer programming language that supports a variety of programming. Today we will give you a detailed introduction of C + + polymorphism of some basic knowledge, in order to facilitate everyone in the learning process can have a full grasp.
Polymorphism can be simply summed up as "one interface, multiple methods", the program is executed to determine the function of the call, it is the core concept of object-oriented programming domain. Polymorphic (polymorphisn), literally meaning multiple shapes.
C + + polymorphism is implemented by virtual functions, which agree that subclasses define member functions once again, and that subclasses define the parent class again as overwrite (override), or override. (Here I think to add, rewrite the words can have two, directly rewrite the member function and rewrite the virtual function, only the ability to rewrite the virtual function as the embodiment of C + + polymorphism) and overloading is to agree to have more than one function with the same name, and these functions of the table is different, agreed to participate in the number of different types of parameters, Or the two are different. The compiler modifies the name of a function of the same name, based on a different list of these functions, resulting in a preprocessing function with different names to overload the problem when a function call of the same name is implemented. But this does not manifest polymorphism.
The real difference between polymorphic and non-polymorphic is whether the function address is early binding or late binding. Assuming that the function is called, it is possible to determine the call address of the function during compiler compilation, and the production code is static, that is, the address is early bound. Assuming that the address of a function call cannot be determined during the compiler, it needs to be determined at execution time, which is late binding.
What is the role of polymorphism, encapsulation can make code modular, inheritance can extend existing code, their purpose is for code reuse. The purpose of polymorphism is to reuse the interface. That is, the function can be invoked through the same interface to the implementation of the respective object, regardless of the object of the class passed over.

  The most common way to use this is to declare a pointer to a base class, use that pointer to a discretionary subclass object, and invoke the corresponding virtual function to implement different methods depending on the sub-class to which it is directed. Assuming that a virtual function is not used, that is, if C + + polymorphism is not utilized, then the corresponding function is called with the base class pointer, and it is always limited to the base class function itself, and cannot be called to a function that has been overridden in subclasses . Because there is no polymorphism, the address of the function call will be certain, and the fixed address will always be called to the same function, which will not implement an interface, the purpose of a variety of methods.

Written questions:

#include <iostream>using namespace Std;class a{public:void foo () {printf ("1\n");} virtual void Fun () {printf ("2\n");}}; Class B:public a{public:void foo () {printf ("3\n");} void Fun () {printf ("4\n");}}; int main (void) {a A; b b; A *p = &a;p->foo ();p->fun ();p = &b;p->foo ();p->fun (); return 0;}
     first P->foo () and P->fuu () is very well understood, itself is a base class pointer, is the base class object, the call is the base class itself function, so the output is 1, 2.
    The second output is 1, 4. P->foo () and P->fuu () are the base class pointers to the subclass object, which formally embodies the use of polymorphism, P->foo () because the pointer is a pointer to a base class, pointing to a fixed offset function, so the point is only the code of the Foo () function of the base class. , so the result of the output is still 1. While the P->fun () pointer is a base-class pointer, the fun to point is a virtual function, because each virtual function has a list of virtual functions, when p call fun () is not directly called the function, but through the virtual function list to find the address of the corresponding function, so depending on the object pointed to, the function address will be different , the address of the fun () function of the corresponding subclass will be found, so the result of the output will also be the result of subclass 4.
Another alternative test method in the subject of the written test. That is,
       B *ptr = (B *) &a;  Ptr->foo ();  ptr->fun (); The
asks the output of these two calls. This is a pointer to a subclass that points to a base class object that is cast to the subclass address. As a result, the output of these two invocations is 3, 2. The
does not quite understand the use of this method, explained from the principle, because B is a subclass pointer, although it is given the base class object address, but Ptr->foo () at the time of invocation, because the address offset is fixed, the offset is the sub-class object offset, So even in the case of a base class object, the function of the subclass is called, although there may be no instantiation of the child class object from beginning to end.
and the call to Ptr->fun () may be due to C + + polymorphism, because it points to a base class object, and through a reference to the virtual function list, the address of the fun () function in the base class is found, so the function of the base class is called. This shows that the polymorphism of the powerful, can adapt to various changes, whether the pointer is a base class or sub-class, can find the correct implementation method.
Summary: 1, there is virtual can occur polymorphic phenomenon//2, does not occur polymorphic (no virtual) call on the original type call #include<iostream>using namespace Std;class base{public : virtual void F (float x) {cout<< "base::f (float)" << x <<endl;} void g (float x) {cout<< "base::g (float)" << x <<endl;} void h (float x) {cout<< "base::h (float)" << x <<endl;}};   Class derived:public base{public:virtual void F (float x) {cout<< "derived::f (float)" << x <<endl;     polymorphic, overlay}void g (int x) {cout<< "derived::g (int)" << x <<endl;   Hide}void H (float x) {cout<< "derived::h (float)" << x <<endl; Hide}};int Main (void) {Derived D;   Base *PB = &d;derived *PD = &d;//Good:behavior depends solely on type of the objectpb->f (3.14f);   Derived::f (float) 3.14pd->f (3.14f);   Derived::f (float) 3.14//bad:behavior depends on type of the Pointerpb->g (3.14f);   Base::g (float) 3.14pd->g (3.14f); Derived::g (int) 3//Bad:behavior depends on type of the pointerPb->h (3.14f);   Base::h (float) 3.14pd->h (3.14f); Derived::h (float) 3.14return 0;}
Confusing hidden rules
It is not difficult to have only different overloads and overrides, but the hidden rules of C + + add to the complexity of the problem.
"Hide" here refers to a function of a derived class that masks a base class function with the same name , such as the following:
(1) Assume that a function of a derived class has the same name as a function of a base class, but the number of parameters is different. At this point, whether or not virtual
keyword, the function of the base class will be hidden (note not to be confused with overloading).
(2) Assume that the function of the derived class has the same name as the function of the base class, and the parameters are the same, but the base class function has no virtual
Keyword At this point, the function of the base class is hidden (be careful not to confuse the overlay).
In the above program:
(1) The function derived::f (float) is covered with base::f (float).
(2) the function derived::g (int) hides base::g (float) instead of overloading.
(3) The function derived::h (float) hides the base::h (float) instead of the overlay.

C + + pure virtual function
First, the definition
A pure virtual function is a virtual function declared in a base class that is undefined in the base class, but requires that whatever derived class defines 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 funtion () =0
Second, the reasons for the introduction
1, in order to facilitate the use of polymorphic features, we often need to define virtual functions in the base class.
2, in very many cases, the base class itself generates objects that are unreasonable. For example, animals as a base class can derive from tigers, peacocks and other sub-categories, but the animals themselves generated objects are obviously unreasonable.
In order to solve the above problems, the concept of pure virtual function is introduced, the function is defined as pure virtual function (method: Virtual ReturnType functions () = 0;), the compiler requirements must be overridden in the derived class to achieve polymorphism. A class with a pure virtual function at the same time is called an abstract class, and it cannot generate objects. This is a very good way to overcome these two problems.
Iii. Concept of similarity
1. Polymorphism
A different implementation action occurs when the same object receives different messages or different objects receive the same message. C + + supports two kinds of polymorphism: compile-time polymorphism, and execution-time polymorphism.
A, compile-time polymorphism: by overloading the function of the implementation
b, the implementation of polymorphism: through virtual function implementation.

2. Virtual function
A virtual function is a member function that is declared as virtual in a base class and once again defined in a derived class, which implements the dynamic of the member functionOverwrite (override)
3. Abstract class
Classes that include pure virtual functions are called abstract classes. Because abstract classes include undefined pure virtual functions,cannot define an object of abstract class。



 

Talking about C + + polymorphism

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.