Call to Virtual function (1)

Source: Internet
Author: User

Definition of virtual function:

A member function declared in a base class as virtual and redefined in one or more derived classes: The virtual function returns the type function name (parameter table) {function Body}, implements polymorphism, and accesses the overridden member function with the same name in the derived class by pointing to the base class pointer or reference of the derived class.

consider the following two classes:
class Base {public:virtual void F ();};
class Derived:base {public:void f ();};
in C + +, there are two types of pointers or references to classes: static types and dynamic types.
Base *b; b = new Derived ();
for B, its static type is the base on the left, and the dynamic type is the derived on the right.
If I call this: B->f (), then this is a polymorphic call because the F () function is virtual. Although I declare that B is a base type, in fact, this f () call is the F () function in the derived class.
It can be simply said that in C + +, if you call a function with a pointer or reference to a class, and the function is virtual, the call is polymorphic, meaning that it invokes the corresponding function of the pointer or the reference dynamic type (that is, the actual type).
Otherwise, the call is non-polymorphic, that is, it will only invoke the corresponding function of the static type of the object.
Note that in other words, except for the "class object pointers, virtual methods" and "class object references. Virtual methods", the others are non-polymorphic calls.
such as: Base B;
B.f ();
This is definitely the F () in the base class of the call; If you remove virtual from the above example, then:
Base *b = new Derived;
b->f ();
It is also called F () in the base class, rather than the F () in its actual type derived class.

Call to Virtual function (1)

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.