C ++ pure virtual class overview

Source: Internet
Author: User

C ++ pure virtual class overview
I. Reasons for the article

The virtual method and virtual class can be said to be a major feature of the c ++ language, and some people may even say it is the essence of the c ++ language. In fact, this is also true, because the Runtime polymorphism is fully embodied in c ++, and virtual is a multi-state service. This is also a c ++ issue that must be understood. At the same time, I think this kind of underlying problems cannot be covered in one article, and I also believe that readers who really want to understand this problem will not read this article, so I just want to look at it, you are also welcome to discuss and correct it.

Ii. Reasons for introduction

In fact, I have written the reason for introducing pure virtual functions in my other article virtual functions and multi-state browsing. But if it is important to say it three times, it is only two times, haha ~~ You also need to know why.

2.1 Definition

Pure virtual functions:A pure virtual function is a virtual function declared in the base class. It is not defined in the base class, but any derived class must define its own implementation method. To implement pure virtual functions in the base class, add "= 0" after the function prototype ".

Pure virtual class:Classes that contain one or more pure virtual functions are called pure virtual classes and abstract classes.

For example, virtual void funtion () = 0

2.2 reason for introduction

1. To facilitate the use of polymorphism, we often need to define virtual functions in the base class.

2. In many cases, it is unreasonable for the base class to generate objects.

For example, an animal can be derived from sub-classes such as tigers and peacocks as a base class, but the object generated by the animal itself is obviously unreasonable. To solve the above problem, the concept of pure virtual Function is introduced, and the Function is defined as a pure virtual Function (method: virtual ReturnType Function () = 0 ;), the compiler requires that the class must be rewritten to implement polymorphism. Classes that contain pure virtual functions are called abstract classes and cannot generate objects. In this way, the above two problems are well solved.

This makes it clear why there are pure virtual classes ~~

Iii. Features of pure virtual classes 3.1 direct features

The list is not necessarily ordered, but it should be listed as much as possible. Please add it.

1. First, the pure virtual class is different from the virtual class. Virtual classes can be instantiated,Pure virtual classes cannot be instantiated, so they will never have objects....... T.T (AlwaysNo object, so miserable !!)

2. If the subclass does not implement pure virtual functions, a considerable number of subclasses also have pure virtual functions, so the subclass is also a pure virtual class.

3. Definitions and usage of other classes are similar to those of general classes, which are roughly as follows:

1) pure virtual classes can have member variables (yes)
2) pure virtual classes can have common member functions (yes)
3) pure virtual classes can have other virtual functions (yes)
4) can pure virtual classes have constructors with parameters? (Yes)
5) Can I explicitly call a parameter-containing constructor of a pure virtual class in the constructor of a pure virtual class (yes)

3.2 description of pure virtual classes in an article

This is what I wrote in an article:

1. An abstract class is a special class that is created for the purpose of abstraction and design.At the upper level of the inheritance hierarchy(Not the absolute upper layer, but also the middle layer or even the bottom layer ).

2. to emphasize that a class is an abstract classConstructor(Set to protected) indicates the access control permission to be protected.

The article also wrote:

3. The main function of an abstract class is to organize the relevant organizations in an inheritance hierarchy and provide them with a public root (not necessarily the root ), the related subclass is derived from this root.

4. abstract classes depict the General Semantics of a group of sub-class operation interfaces. These semantics are also passed to sub-classes. In general, an abstract class only describes this group of child classes.Common Operation InterfacesAnd the complete implementation is left to the subclass.

5. the abstract class can only be used as the base class (in most cases, it is the base class of other classes, but the abstract class may also be a subclass ).

6. You can define a pointer and reference pointing to an abstract class. This pointer can point to its derived class to achieve polymorphism.

Iv. Examples of pure virtual classes

Examples used as interfaces:

#include
  
   #include
   
    #include
    
     #includeusing namespace std;class animal{protected:    animal(){}    virtual void  eat(const string name) =0;};class dog:public animal{public:    vector
     
       m_food;    void eat(const string name);    void push_back(const string name);};void dog::eat(const string name){    vector
      
       ::iterator iter=std::find(m_food.begin(),m_food.end(),name); if (m_food.end() !=iter) { cout<
       
      
     
    
   
  

Another good example is a multi-state instance:

# Include  Using namespace std; const double PI = 3.14159; class Shapes // abstract class {protected: int x, y; public: void setvalue (int d, int w = 0) {x = d; y = w;} virtual void disp () = 0; // pure virtual function}; class Square: public Shapes {public: void disp () {cout <rectangular area: <  Setvalue (10, 5); ptr [0]-> disp (); ptr [1] = & c1; ptr [1]-> setvalue (10 ); ptr [1]-> disp (); return 0 ;}  
V. Pure virtual class and virtual function table

There is such a problem:

We know that a class with virtual functions in C ++ has a corresponding virtual function table. Is there a virtual table in a pure virtual class? How can I call a pure virtual function if so?

Intuitively, there should be. However, since it is a pure virtual class, it means that its object will never be created, it does not seem necessary to maintain a virtual table.

Design a program to verify:

class VirtualBase{public: VirtualBase() { // call pure virtual function through a non virtual function in base class's constructor non_virtual_fun(); } void non_virtual_fun() { virtual_fun(); } virtual void virtual_fun() = 0;};class Derived: public VirtualBase{public: virtual void virtual_fun(){}};int main(int argc, const char* argv[]){ size_t size = sizeof(VirtualBase); Derived d;}

Analysis:

(1) sizeof (VirtualBase) returns 4 instead of 1 representing the empty class. This indicates that there is a virtual table pointer inside it, while a virtual table pointer exists, it is very likely that there is a virtual table.

(2) Through the above program, we can call the VirtualBase constructor when instantiating Derived. In this case, we can view the this pointer in the watch window, there is indeed a virtual table pointer pointing to a virtual table.

A pure virtual function is called through a non-virtual function in the constructor. Although this pure virtual function is implemented in Derived, it is still in the base class constructor. Therefore, pure virtual function called-Error

Virtual classes require virtual tables. One reason I can think of is that when override in multiple Derived classes, we need to ensure that the transformed function is at the correct offset address, to ensure that the address is correct, it is important to prepare a template in advance.

 

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.