Pure virtual functions and abstract classes in C++

In C++, a virtual function can be declared as a pure virtual function, and the syntax format is:

virtual return value type function name (function parameter) = 0;

A pure virtual function has no function body, only a function declaration. Adding it at the end of the virtual function declaration =0indicates that the function is a pure virtual function.

The last one =0does not mean that the function return value is 0, it only plays a formal role, telling the compilation system "this is a pure virtual function".

A class containing pure virtual functions is called an abstract class. The reason why it is said to be abstract is that it cannot be instantiated, that is, it cannot create objects. The reason is obvious. A pure virtual function has no function body, is not a complete function, cannot be called, and cannot allocate memory space for it. Abstract classes usually serve as base classes, allowing derived classes to implement pure virtual functions. Derived classes must implement pure virtual functions before they can be instantiated. Examples of using pure virtual functions:

    #include <iostream>
    using namespace std;
    //线
    class Line{
    public:
        Line(float len);
        virtual float area() = 0;
        virtual float volume() = 0;
    protected:
        float m_len;
    };
    Line::Line(floa

Guess you like

Origin blog.csdn.net/shiwei0813/article/details/132768396