C + + polymorphism analysis

Source: Internet
Author: User

Compile-time polymorphism--function overloading

The compiled intermediate code, such as GCC , produces an . o file. At this time is not assembly language) function name changes, look at the following two examples.

void Cc_show (const char*str), _Z7CC_SHOWPKC

void cc_show (int x), _z7cc_showi

As you can see, the function names are actually different, related to the return value, function name, and number of references.

The rule for function overloading is that the number or type of arguments must be different, so there is no confusion.

Dynamic binding of polymorphic--virtual at execution time

At compile time, the compiler will be a class with a virtual function and a class with a virtual function /A subclass of the base class / . Create a virtual function table (that is, virtual table). The table is a one-dimensional array that holds the address of each virtual function.

So how do you locate a virtual table? The compiler also provides a virtual table pointer (that is, vptr) for each class object. This pointer points to the virtual table of the class to which the object belongs. When the program executes. Initialize the vptr According to the type of the object , so that vptr the correct point of the virtual table of their class. Therefore, when the virtual function is called, it is OK to find the correct function.

A virtual function table is a class, in place of an object. The object only needs to keep a pointer to the virtual function table it can be in the class. If a class is multiple inheritance, and other parents also have virtual functions. Then this class needs to maintain multiple virtual function tables.

C + + polymorphism analysis

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.