C + + polymorphism

Source: Internet
Author: User

1.1 The concept of polymorphism

In object-oriented language, many different implementations of interfaces are polymorphic, which can be simply summed up as "one interface, many methods".

Polymorphism (polymorphism) is an important feature of object-oriented programming. If a language supports only classes and does not support polymorphism, it cannot be called an object-oriented language, but can be said to be object-based.

Referring to Charlie Calverts's description of polymorphism--polymorphism is a technique that allows you to set a parent object to be equal to one or more of his sub-objects, after which the parent object can operate differently depending on the attributes of the child object currently assigned to it (excerpt from the "DELPHI4 Programming Insider"). To put it simply, it is a sentence: A pointer to the parent class type is allowed to be assigned a pointer to the child class type. Polymorphism is implemented in Object Pascal and C + + through virtual functions.

1.2 Forms

Polymorphism : The same operation acts on different objects, can have different interpretations, and produces different execution results. At run time, you can invoke methods in the derived class by pointing to a pointer to the base class. Polymorphism is the method that allows the name of the methods, parameters or return values that can be passed in or returned by the parent type.

The polymorphism of C + + is embodied in two aspects of running and compiling. Run-time polymorphism is dynamic polymorphism, and its specific referenced objects are determined at run time. Compile-time polymorphism is static polymorphism, which can be used to determine the form of an object at compile time. 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.

in C + +, the implementation of polymorphism has the following methods: virtual function, abstract class, overlay, template (overloaded and polymorphic independent). polymorphism in OC: different objects respond differently to the same message. Subclasses can override methods of the parent class C + + uses virtual functions to implement polymorphism, and virtual functions allow subclasses to redefine member functions, while subclasses redefine the parent class as overwrite (override), or override. (There can be two kinds of rewriting, directly overriding the member function and overriding the virtual function, only to override the virtual function to be counted as the C + + polymorphism)  
Overloading, however, allows multiple functions with the same name, with different parameter
lists, different parameter types, or different parameters. 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.
 1.3 Effects encapsulation can make code modular, inheritance can extend existing code, and their purpose is for 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.

 1.4 Example

#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;  }

 


    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.


Examples of alternative testing methods. 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.

    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 (Flo          at) "<< 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<< "Deri   Ved::f (float) "<< x <<endl;     Polymorphic, overwrite} void g (int x) {cout<< "derived::g (int)" << x <<endl; Hide} void H (float x) {cout<< "derived::h (float)" << x <<endl   ;      Hidden}}; int main (void) {DerivedD          Base *PB = &d;          Derived *PD = &d;   Good:behavior depends solely on type of the object Pb->f (3.14f);   Derived::f (float) 3.14 pd->f (3.14f);   Derived::f (float) 3.14//Bad:behavior depends on type of the pointer pb->g (3.14f);   Base::g (float) 3.14 pd->g (3.14f);   Derived::g (int) 3//Bad:behavior depends on type of the pointer pb->h (3.14f);   Base::h (float) 3.14 pd->h (3.14f);      Derived::h (float) 3.14 return 0;   }

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.
"Hide" here 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, the function of the base class is hidden, regardless of the virtual keyword (Note that it is not confused with overloading).
(2) If the function of the derived class has the same name as the function of the base class, and the parameters are the same, the base class function does not have the 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 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 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 many cases, the base class itself is unreasonable to generate objects. 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 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 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.


Iii. Concept of similarity


1. Polymorphism
A different implementation action occurs 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: by overloading the function of the implementation
B, run-time 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 redefined in a derived class to implement dynamic override of a member function (override)
3. Abstract class
Classes that contain pure virtual functions are called abstract classes. Because an abstract class contains a pure virtual function that is not defined, an object of an abstract class cannot be defined.

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.