Sobes.tech
Junior — Middle

Is it possible in C++ to define a class containing only pure virtual functions, and prevent it from being instantiated directly?

sobes.tech AI

Answer from AI

Yes, in C++ it is possible to define a class that contains only pure virtual functions, and such a class cannot be instantiated directly. This class is called an abstract class. It serves as an interface or a base class for derived classes that must implement all pure virtual functions.

Example:

class Interface {
public:
    virtual void doSomething() = 0; // pure virtual function
    virtual ~Interface() = default;
};

// Cannot create an object of Interface directly:
// Interface obj; // compilation error

class Implementation : public Interface {
public:
    void doSomething() override {
        // implementation
    }
};

int main() {
    Implementation impl;
    impl.doSomething();
}