Virtual Function

Pure Virtual Function

“Pure virtual” methods are abstract in parent, and defined later by children. We declare a pure virtual method by assigning 0 in the declaration.

Relation to Abstract Class and Concrete Class:

  • A class that declares a pure virtual function is an Abstract Class (cannot be instantiated as objects)
  • A class that overrides ALL of its parents pure virtual functions is called a Concrete Class (can be instantiated)
class Test {   
public:
    // Pure Virtual Function
    virtual void show() = 0;
};

Danger

If you declare a pure virtual function in the base class, you need to make sure that the derived class has an implementation for it.

Pure Virtual Methods can STILL be implemented in the base class

Pure virtual methods don’t have to be implemented, but they still can be. They require an implementation if they will be called.

”= 0 means derived classes must provide an implementation, not that the base class cannot provide an implementation”. See this StackOverflow thread. So what is the point of providing an implementation in the Base Class for a pure virtual function, if the derived classes must ALWAYS provide an implementation anyways? Because there are use cases.

The derived class can explicitly call the base class implementation (if access permissions allow it) by using a fully-scoped name:

class A {
public:
    virtual void f() = 0;
};
 
void A::f() {
    cout<<"Test"<<endl;
}
 
class B : public A {
 
    virtual void f() {
        // class B doesn't have anything special to do for f()
        //  so we'll call A's
        A::f();
    }
 
};

The use case I can think of off the top of my head is when there’s a more-or-less reasonable default behavior, but the class designer wants that sort-of-default behavior be invoked only explicit

Uses cases:

  • When you want derived classes to always perform their own work but also be able to call a common set of functionality.