c-plus-plus
  1. c-plus-plus-virtual-function-vs-pure-virtual-function-in-c

Virtual function vs Pure virtual function in C++

Virtual functions and pure virtual functions are two important concepts in object-oriented programming with C++. Understanding the difference between them is essential for designing and implementing effective, modular and scalable software.

Syntax

A virtual function is a function that can be overriden in derived classes:

class Base {
public:
    virtual void foo() {
        // implementation
    }
};

class Derived : public Base {
public:
    void foo() override {
        // implementation
    }
};

A pure virtual function is a function that must be overridden by any derived class:

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

class Derived : public Base {
public:
    void foo() override {
        // implementation
    }
};

Example

#include <iostream>
using namespace std;

class Base {
public:
    virtual void foo() {
        cout << "Base::foo" << endl;
    }
};

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

int main() {
    Base* b = new Derived();
    b->foo();
    return 0;
}

Output

Derived::foo

Explanation

In the above example, we have a base class and a derived class. The base class has a virtual function called "foo", which is overridden in the derived class. When we create an object of the derived class and call the "foo" function using a pointer of the base class type, the function executed is that of the derived class, not that of the base class.

Use

Virtual functions are used when a base class needs to be extended by a derived class. Pure virtual functions are used when a base class specifies an interface that must be implemented by all derived classes.

Important Points

  • Virtual functions allow derived classes to override functions of the base class.
  • Pure virtual functions are used to specify an interface that must be implemented by all derived classes.
  • Pure virtual functions are declared using "= 0" syntax.
  • Abstract classes contain at least one pure virtual function and cannot be instantiated.
  • Virtual functions can be overridden using the "override" keyword.

Summary

In summary, virtual functions and pure virtual functions are two different concepts in C++ that allow derived classes to override functions of the base class. Pure virtual functions specify an interface that must be implemented by all derived classes, while virtual functions can be optionally overridden. Both concepts are important for designing and implementing effective, modular, and scalable software.

Published on: