There is a pure virtual function in the c++ class, then this class cannot be instantiated

A class is called an abstract class if it contains pure virtual functions. Abstract classes cannot be instantiated directly (that is, objects of abstract classes cannot be created) because they have pure virtual functions that are not implemented.

A pure virtual function is a virtual function declared in a base class without a concrete implementation, defined by assigning it a value of 0. A derived class must implement a pure virtual function in the base class to be instantiated.

The main purpose of an abstract class is to serve as a base class for other classes, provide interfaces and specifications for derived classes, and force derived classes to implement specific functions. Therefore, abstract classes can only be used as base classes to provide an abstract concept.

The following is an example illustrating the definition and usage restrictions of an abstract class:

class Shape {
public:
    virtual void draw() = 0;  // 纯虚函数,没有实现体
};

class Circle : public Shape {
public:
    void draw() override {
        // 实现绘制圆形的代码
    }
};

int main() {
    // Shape shape;  // 错误!无法实例化抽象类

    Circle circle;  // 正确!Circle 是一个具体的派生类,实现了所有纯虚函数

    Shape* shapePtr = &circle;  // 可以通过指针或引用访问抽象类的派生类对象

    shapePtr->draw();  // 调用派生类的实现
}

It should be noted that in the derived class, all pure virtual functions in the base class must be implemented, otherwise the derived class will still be regarded as an abstract class.

In summary, classes (abstract classes) containing pure virtual functions cannot be instantiated directly, but can be used as base classes to be implemented and used by derived classes.

In the live555 source code, the parent class of the BasicUsageEnvironment0 class is the UsageEnvironment class. Since the BasicUsageEnvironment0 class does not implement all the pure virtual functions of the parent class, the BasicUsageEnvironment0 class is also an abstract class and cannot be instantiated directly .

The parent class of the BasicUsageEnvironment class is the BasicUsageEnvironment0 class, which implements other pure virtual functions that the BasicUsageEnvironment0 class does not implement, and does not declare new pure virtual functions, so this class is not an abstract class, because its constructor BasicUsageEnvironment is a protected attribute, so this The class cannot be instantiated directly , and the pointer to BasicUsageEnvironment can only be obtained through the createNew function defined inside the class, and then the class can be used through the pointer.

Guess you like

Origin blog.csdn.net/qq_26093511/article/details/131808813