C + + Primer Learning Notes (14)--virtual function implementation mechanism, pure virtual function

Source: Internet
Author: User

Read the relevant books before the text, referring to some other people's blog, here thank you for sharing! Hope that they and everyone in the language of learning on the road gradually, go down ~ ~ ~

The three basic traits of C + + are encapsulation, inheritance, and polymorphism, the previous article said.

Polymorphism is the separation of interfaces from the implementation. The use of image language interpretation is to achieve the common method, but the individual differences and adopt different strategies.

Polymorphism includes static polymorphism and dynamic polymorphism, which are implemented in the process of compiling and running. The dynamic polymorphism is realized by virtual function, and its realization mechanism embodies the mystery of C + +.

1. Implementation mechanism of virtual function

Virtual functions are member functions that are decorated with the virtual keyword and are used to implement polymorphism.

Two important keywords reveal the mystery of it: virtual tables, virtual pointers . Each class uses a virtual table, and each class object uses a virtual pointer.

This is illustrated below:

class A{public:    virtualvoidf();    virtualvoid g();private:    intpublic A{public:    voidf();   // 覆盖父类A中的虚函数f()private:    int b; };

Because A has virtual void f (), and G (), the compiler prepares a virtual table Vtablea for Class A, which reads as follows:

b inherits A, so there is also a virtual function that inherits from a, so B also has a virtual table Vtableb:

PS: Because B:: G is rewritten, so g of the virtual table of B is the entry address of b::g, and F is a:: G's entry address.

When implementing B BT; When defining a class object, when the compiler allocates space, except for the int a member of a, the int b member of B, and the pointer vptr to the virtual table Vtableb to B, the object BT is laid out as follows:

Where the virtual table pointer is always at the front.

When you execute the following statement:

A *pa = &bt;  //一个A 类型的指针,指向B类型的对象bt

PA->g () is actually a virtual table Vtableb that pointer vptr to B, and then goes inside to look for the G () function. As you can see, Vtableb is B: g (), which is B's own g (), not a G ().
This is polymorphism.

Summarize:

To know the mechanism of the virtual function to implement polymorphism, remember the virtual table and virtual pointer. It is easy to understand this mechanism by listing the virtual tables of the parent and child classes and the virtual pointers to the subclass objects.

2. Pure virtual function

Many times, it is meaningless to define an object of a class, for example, an animal, which can derive a subclass such as an elephant, a lion, a monkey, but the animal itself produces an object that has no practical meaning. In order to solve this problem, the concept of pure virtual function is proposed.
If the defined virtual function is:

virtualvoid animals(stringint age){}

Then here is the pure virtual function:

virtualvoid animals(stringint0;   // 函数体直接为0 的虚函数

A class with a pure virtual function is called an abstract class , is a simple interface, an abstract class itself is instantiated, that is, the object cannot be generated, and must be instantiated in the derived class.

Under what circumstances are pure virtual functions used?

    • When you want to abstract a method in a base class, and the base class can only be inherited, you cannot instantiate

    • This method must be implemented in a derived class

For the above two points are illustrated separately:

1) Abstract classes cannot be instantiated

For example: Define a class of shapes (Cshape), but all shapes we require to be able to display ourselves, so define a class as follows:

class Cshape{    virtual show(){}};

We do not want to instantiate this class, we first think of the function body {} of the show () is deleted and changed to Virtual Show ();

At this point, if you attempt to instantiate Cshape shape; This is actually able to compile, only when the connection error.

So how can you make an error when compiling?

~ ~ with pure virtual function:

class Cshape{    0// 纯虚函数不能实例化};

2) The method must be implemented in a derived class

As shown in the example above, show () must be implemented in each subclass, that is, redefine its show () function in subclasses, and, if not defined, error at compile time:

// 定义Cshape 的派生类,忘了定义show()public Cshape{  public:    voidmsg()    {        " 这是一个点。" << endl;    }private:    float x;    float y;};// 下面实例化 CPoint 类的时候就会报错!!!CPoint point1;

In the compile time will be an error!!!

~~~~
Is this a way to prevent the implementation of a base class in a derived class? (^__^)

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + Primer Learning Notes (14)--virtual function implementation mechanism, pure 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.