Talking about C + + polymorphism

Source: Internet
Author: User

The 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 the C + + polymorphism of some basic knowledge, in order to facilitate everyone in the learning process in this can have a full grasp.
Polymorphism can be simply summed up as "one interface, many methods", the program at runtime to determine the function of the call, it is the core concept of object-oriented programming domain. Polymorphic (polymorphism), literally meaning multiple shapes.
C + + polymorphism is implemented through virtual functions, which allow subclasses to redefine member functions, while subclasses redefine the parent class as overwrite (override), or override. (Here I think to add that there can be two kinds of rewrite, directly rewrite the member function and rewrite the virtual function, only to override the virtual function to be counted as the embodiment of C + + polymorphism) and overloading is allowed to have multiple functions with the same name, and the parameters of these functions are different, the number of parameters is different, the parameter type is different, 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, producing preprocessing functions of 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. If a function is called, the call address of the function can be determined during compiler compilation, and the production code is static, which means that the address is early bound. If the address of a function call cannot be determined during the compiler, it needs to be determined at run time, which is a late binding.
So what is the role of polymorphism, encapsulation can make code modular, inheritance can extend existing code, their purpose is to code reuse. The purpose of polymorphism is to reuse the interface. In other words, regardless of what is passed to the object of that class, functions can be called through the same interface to adapt to the implementation of the respective object.

  The most common usage is to declare a pointer to a base class, use it to point to any subclass object, invoke the corresponding virtual function, and implement a different method depending on the sub-class to which it is directed. If you do not use a virtual function, that is, you are not using C + + polymorphism, when you invoke the corresponding function using the base class pointer, it will always be limited to the base class function itself, and cannot be called to a function that has been overridden in a subclass. 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:

[CPP]View Plaincopy
  1. #include <iostream>
  2. Using namespace std;
  3. Class A
  4. {
  5. Public
  6. void foo ()
  7. {
  8. printf ("1\n");
  9. }
  10. virtual void Fun ()
  11. {
  12. printf ("2\n");
  13. }
  14. };
  15. Class B: Public A
  16. {
  17. Public
  18. void foo ()
  19. {
  20. printf ("3\n");
  21. }
  22. void Fun ()
  23. {
  24. printf ("4\n");
  25. }
  26. };
  27. int main (void)
  28. {
  29. A;
  30. b b;
  31. A *p = &a;
  32. P->foo ();
  33. P->fun ();
  34. p = &b;
  35. P->foo ();
  36. P->fun ();
  37. return 0;
  38. }

The first P->foo () and P->fuu () are very well understood, they are the base class pointers, they are the base class objects, the call is the function of the base class itself, so the output is 1, 2.
The second output is 1, 4. P->foo () and P->fuu () are the base class pointers to sub-class objects, formally manifesting the use of polymorphism, P->foo () because the pointer is a base-class pointer, pointing is a fixed offset function, so this point is only the base class Foo () function code, So the result of the output is still 1. While the P->fun () pointer is a base-class pointer, the fun 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 according to the object pointed to different, 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.
There is also an alternative test method in the written question. That
b *ptr = (b *) &a;  Ptr->foo (); Ptr->fun ();
Ask for 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.
Not very understanding of this usage, explained from the principle, because B is a sub-class 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 is pointed, Or a function called a subclass, although there may be no instantiation of the subclass object from beginning to end.
The invocation of Ptr->fun () may also be due to C + + polymorphism, because it points to a base class object that, through a reference to a virtual function list, finds the address of the fun () function in the base class, and therefore calls the function of the base class. 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.

[CPP]View Plaincopy
  1. Summary: 1, there is virtual can occur polymorphic phenomenon
  2. 2. No polymorphic (no virtual) calls are invoked on the original type
  3. #include <iostream>
  4. Using namespace std;
  5. Class Base
  6. {
  7. Public
  8. virtual void F (float x)
  9. {
  10. cout<<"base::f (float)" << x <<endl;
  11. }
  12. void g (float x)
  13. {
  14. cout<<"base::g (float)" << x <<endl;
  15. }
  16. void H (float x)
  17. {
  18. cout<<"base::h (float)" << x <<endl;
  19. }
  20. };
  21. Class Derived: Public Base
  22. {
  23. Public
  24. virtual void F (float x)
  25. {
  26. cout<<"derived::f (float)" << x <<endl; //multi-state, cover
  27. }
  28. void g (int x)
  29. {
  30. cout<<"derived::g (int)" << x <<endl; //Hide
  31. }
  32. void H (float x)
  33. {
  34. cout<<"derived::h (float)" << x <<endl; //Hide
  35. }
  36. };
  37. int main (void)
  38. {
  39. Derived D;
  40. Base *PB = &d;
  41. Derived *PD = &d;
  42. //Good:behavior depends solely on type of the object
  43. Pb->f (3.14f); //Derived::f (float) 3.14
  44. Pd->f (3.14f); //Derived::f (float) 3.14
  45. //Bad:behavior depends on type of the pointer
  46. Pb->g (3.14f); //Base::g (float) 3.14
  47. Pd->g (3.14f); //derived::g (int) 3
  48. //Bad:behavior depends on type of the pointer
  49. Pb->h (3.14f); //Base::h (float) 3.14
  50. Pd->h (3.14f); //Derived::h (float) 3.14
  51. return 0;
  52. }

Confusing hidden rules
It is not difficult to distinguish between overloading and overwriting, but the hidden rules of C + + increase the complexity of the problem abruptly.
Over here"Hidden" refers to a function of a derived class that masks a base class function with the same name as the following rule:
(1) If the function of the derived class has the same name as the function of the base class, but the parameters are different. At this point, whether or not virtual
keyword, the function of the base class is hidden (note that it is not confused with overloading).
(2) If a function of a derived class has the same name as a function of the base class and the parameters are the same, the base class function has no virtual
Key word. 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
  One, definition
  pure virtual function is a virtual function declared in the base class, it is not defined in the base class. However, any derived class is required to define its own implementation method. The method of implementing a pure virtual function in a base class is to add "=0"
  virtual void funtion () =0
II, introducing the reason
    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. For example, animals as a base class can be derived from tigers, peacocks and other sub-categories, but the animals themselves generated objects are obviously unreasonable.
  In order to solve the above problem, the concept of pure virtual function is introduced, the function is defined as pure virtual function (method: Virtual ReturnType functions () = 0;), then the compiler requires that it must be overridden 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. This is a good solution to both of these problems.
Three, similar concepts
   1, polymorphism
  refers to different implementation actions when the same object receives different messages or when different objects receive the same message. C + + supports two kinds of polymorphism: compile-time polymorphism, run-time polymorphism.
  A, compile-time polymorphism:
  B, run-time polymorphism with overloaded functions: implemented by virtual functions.

  2, virtual function
  virtual function is a member function that is declared as virtual in the base class and redefined in the derived class to implement the dynamic of the member function overwrite (override)
  3, abstract class
  class containing pure virtual functions is called abstract class. Because an abstract class contains a pure virtual function that is not defined, The object of an abstract class cannot be defined.

Talking about C + + polymorphism

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