The role of virtual function

Source: Internet
Author: User

The dynamic polymorphism implemented by virtual function is the same kind of object in the same family, and responds differently to the same function call. Virtual functions are used in the following ways:

(1) Declare member functions as virtual functions in the base class with virtual. This allows you to redefine this function in a derived class, give it new functionality, and be easily invoked.

When you define a virtual function outside of a class, you do not have to add virtual.

(2) Redefining this function in a derived class requires that the function name, function type, number of function arguments, and type are all the same as the virtual functions of the base class, and redefine the function body according to the needs of the derived class.

C + + stipulates that when a member function is declared as a virtual function, the function with the same name in its derived class automatically becomes a virtual function. Therefore, when a derived class re-declares the virtual function, you can add virtual, or do not add, but it is customary to declare the function at each layer to add virtual, so that the program clearer.

If the virtual function of the base class is not redefined in the derived class, the derived class simply inherits the virtual function of its immediate base class.

(3) Define a pointer variable that points to the base class object and point it to the object in the same class family that needs to call the function.

(4) This virtual function is called through the pointer variable, which is called the function with the same name as the object that the pointer variable points to.

The role of virtual function

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.