Sobes.tech
Junior — Middle

Can you explain what it means to call a virtual function without an implementation in the base class?

sobes.tech AI

Answer from AI

In C++, calling a virtual function without an implementation in the base class means that this function is declared as pure virtual, using the syntax = 0 in the declaration. This makes the class abstract, and objects of such a class cannot be created.

If you try to call such a function directly from the base class, where there is no implementation, the program will either not compile or, if the call is made through a pointer/reference to a derived class where the function is implemented, the call will go to the derived class's implementation.

Example:

class Base {
public:
    virtual void foo() = 0; // pure virtual function
};

class Derived : public Base {
public:
    void foo() override {
        std::cout << "Implementation in Derived" << std::endl;
    }
};

int main() {
    Derived d;
    Base* b = &d;
    b->foo(); // call to the implemented Derived function
}

If you try to call foo() inside the constructor of the base class, where there is no implementation, it will lead to a runtime error because virtual calls in constructors do not work polymorphically.