C ++ abstract class overview, abstract class

Source: Internet
Author: User

C ++ abstract class overview, abstract class
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 ".

Abstract class:Classes that contain one or more pure virtual functions are called abstract classes, and some are also called pure virtual classes. My understanding is about the definition or a certain correct statement, that is, it is better to select an abstract class.

However, Baidu encyclopedia's definition of pure virtual classes is another saying: All functions are pure virtual functions. Pure virtual classes can have member variables. Pure virtual classes cannot be instantiated.

Another concept is "virtual base class", but this is the concept of multi-inheritance in c ++ and will be discussed later.

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 abstract classes exist ~~

Iii. Features of abstract classes 3.1 direct features

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

1. the abstract class is different from the virtual class. Virtual classes can be instantiated,Abstract classes cannot be instantiated, so they 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 an abstract class.

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

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

3.2 description of abstract 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. Example of an abstract class

Examples used as interfaces:

#include<iostream>#include<string>#include<vector>#include<algorithm>using namespace std;class animal{protected:    animal(){}    virtual void  eat(const string name) =0;};class dog:public animal{public:    vector<string> m_food;    void eat(const string name);    void push_back(const string name);};void dog::eat(const string name){    vector<string>::iterator iter=std::find(m_food.begin(),m_food.end(),name);    if (m_food.end() !=iter)    {        cout<<"Dog eat "<<*iter<<endl;    }}void dog::push_back(const string name){    if (m_food.end() ==std::find(m_food.begin(),m_food.end(),name))    {        m_food.push_back(name);    }}int main(void){    dog d;    d.push_back("bone");    d.eat("bone");    return 0;}

Another good example is a multi-state instance:

# Include <iostream> 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:" <x * y <endl ;}}; class Circle: public Shapes {public: void disp () {cout <"circular area:" <PI * x <endl ;}}; int main () {Shapes * ptr [2]; // define the array of object pointers, Square s1; Circle c1; ptr [0] = & s1; ptr [0]-> setvalue (10, 5 ); ptr [0]-> disp (); ptr [1] = & c1; ptr [1]-> setvalue (10); ptr [1]-> disp (); return 0 ;}
V. abstract classes and virtual function tables

There is such a problem:

We know that a class with virtual functions in C ++ has a corresponding virtual function table, so does the abstract class have virtual tables? If so, how can we call pure virtual functions?

Intuitively, there should be. However, since it is an abstract 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

Abstract 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.

-END-

References

[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 statement: you are welcome to repost it. Just specify the source! If you do not like it, please leave a message to explain the reason and step on again. Thank you. I can also know the reason and keep improving !!

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.