C + + pure virtual class overview

Source: Internet
Author: User
Tags function prototype

First, the article for the reason

Virtual method and virtual class can be said to be a major feature of the C + + language, and even some people say that the essence of C + + language, in fact, there is a certain reason, because the runtime polymorphism in C + + embodies incisively and vividly, and virtual is for the polymorphic services. This is also a must understand the C + + problem, so with this article. At the same time, I think this kind of bottom-level problem is impossible to cover, and I believe that the readers who really want to understand this problem will not only read my article, so it is only a small overview, and welcome discussion and correction.

Second, the reasons for the introduction

In fact, the reason for the introduction of pure virtual function I am in my other article virtual function and polymorphic small to write, but the important words three times, but also only two times, haha ~ ~ Know it also need to know why

2.1 Definitions

Pure virtual function: 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.

pure Virtual Class: A class containing one or more pure virtual functions, called pure virtual class, also called abstract class.

such as: virtual void funtion () =0

2.2 Introduction Reason

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.

So it is clear that the reason for pure virtual class ~ ~

Three, pure virtual class characteristics 3.1 directly on the characteristics

List of not necessarily in order, but try to list, welcome to add

1, the first explanation: pure virtual class is different from the virtual class. A virtual class can be instantiated, but a pure virtual class cannot be instantiated, and there will never be an object ... T.T ( never object, so miserable!!) )

2, if the subclass does not implement pure virtual function, quite a subclass also has pure virtual function, so the subclass is also pure virtual class.

3, the definition and use of other classes are similar to the general category, roughly the following places:

1) Pure virtual classes can have member variables (yes)
2) Pure virtual class can have ordinary member function (CAN)
3) Pure virtual class can have other virtual functions (CAN)
4) Can a pure virtual class have a constructor with parameters? Can
5) Is it possible to explicitly invoke a parameter constructor of a pure virtual class in the constructor of a derived class of a pure virtual class (yes)

3.2, an article on the Pure virtual class description

One article wrote:

1, abstract class is a special class, it is for the purpose of abstraction and design, it is in the inheritance hierarchy of the upper layer (rather than the absolute upper, it may be the middle, or even the bottom).

2. In practice, in order to emphasize that a class is an abstract class, the constructor (set to protected) of the class can be described as Protected Access control permissions.

The article also writes:

3. The primary function of an abstract class is to organize the relevant organization in an inheritance hierarchy by providing them with a common root (which is not necessarily the root), derived from the root of the related subclass.

4. Abstract class depicts the general semantics of the operation interface of a set of sub-classes, which are also passed to subclasses. In general, abstract classes describe only the common operating interfaces of this set of subclasses, and the complete implementation is left to subclasses.

5. Abstract classes can only be used as base classes (most cases are base classes of other classes, but abstract classes themselves may also be subclasses).

6. You can define pointers and references to abstract classes, which can point to its derived classes for polymorphism.

Four, pure virtual class example

Examples of use as interfaces:

#include <iostream>#include <string>#include <vector>#include <algorithm>using namespace STD;classanimal{protected: Animal () {}Virtual voidEatConst stringName) =0;};classDog Publicanimal{ Public: vector<string>M_food;voidEatConst stringname);voidPush_back (Const stringname);};voidDog::eat (Const stringName) { vector<string>:: Iterator iter=STD:: Find (M_food.begin (), M_food.end (), name);if(M_food.end ()!=iter) {cout<<"Dog eat"<<*iter<<endl; }}voidDog::p ush_back (Const stringName) {if(M_food.end () = =STD:: Find (M_food.begin (), M_food.end (), name)) {m_food.push_back (name); }}intMainvoid) {Dog D; D.push_back ("Bone"); D.eat ("Bone");return 0;}

Another good example of polymorphic examples:

#include <iostream>usingnamespace Std;Const DoublePi=3.14159; Class Shapes//abstract class{protected:intx, y; Public:void SetValue(intDintw=0) {x=d;y=w;}Virtual voidDisp () =0;//Pure virtual function};class Square: Publicshapes{ Public:void disp() {cout<<"Rectangular area:"<<x*y<<endl; }};class Circle: Publicshapes{ Public:void disp() {cout<<"Circle Area:"<<PI*x*x<<endl; }};intMain () {Shapes *ptr[2];//Define an array of object pointersSquare S1;    Circle C1; ptr[0] = &s1; ptr[0]->setvalue (Ten,5); ptr[0]->disp (); ptr[1] = &c1; ptr[1]->setvalue (Ten); ptr[1]->disp ();return 0;}
Pure virtual class and virtual function table

There is a problem:

We know that C + + has a virtual function of the class will have a corresponding virtual function table, then the pure virtual class has a virtual table, if some words how to call pure virtual function?

Intuitively speaking, there should be. However, since it is a pure virtual class, it means that its object will never be created, then maintaining a virtual table seems to be not necessary.

Design a program to verify:

Class virtualbase{ Public:Virtualbase()    {//Call pure virtual function through a non virtual function in base class ' s constructorNon_virtual_fun (); }voidNon_virtual_fun () {virtual_fun (); }Virtual voidVirtual_fun () =0;}; Class Derived: Publicvirtualbase{ Public:Virtual void Virtual_fun(){}};intMainintargcConst Char* argv[]) {size_t size =sizeof(virtualbase); Derived D;}

Analysis:

(1) sizeof (virtualbase) returns 4 instead of 1 for an empty class, which means that there is a virtual table pointer inside it, and there is a virtual table pointer, so there is a good chance of having a virtual table.

(2) through the above program, we can instantiate the derived when the Virtualbase constructor, you can view the this pointer in the Watch window, there is indeed a virtual table pointer to a virtual table.

A pure virtual function is called through a non-virtual function in the constructor-although the pure virtual function is implemented in derived, it is also in the constructor of the base class, so the pure virtual function is called-error

A pure virtual class needs a virtual table, I can think of one reason is that when overridden in multiple derived classes, we need to ensure that the rewritten function is at the correct offset address, in order to ensure that the address is correct, it is more important to prepare a template beforehand.

-end-

Reference documents

[1] http://blog.csdn.net/goondrift/article/details/19705797
[2] http://blog.csdn.net/Slience_Perseverance/article/details/20536277
[3] Http://www.cnblogs.com/baiyanhuang/archive/2011/03/07/1976445.html

Copyright NOTICE: Welcome Reprint, note The source is good! If you do not like please leave a message to explain why again step on Oh, thank you, I can also know the reason, continuous progress!!

C + + pure virtual class overview

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.