Programming Language

Pure Virtual Function

A pure virtual function is a virtual function that you want to force derived classes to override. If a class has any overridden pure virtuals, it is an “abstract class” and you can’t create objects of that type.

class AbstractClass {
// declare a pure virtual function:
// this class is now abstract
virtual void f(int) = 0;

class StillAbstract : public AbstractClass {
// does not override f(int),
// so this class is still abstract

class Concrete : public StillAbstract {
// finally overrides f(int),
// so this class is concrete
void f(int) { /*…*/ }

AbstractClass a; // error, abstract class
StillAbstract b; // error, abstract class
Concrete c; // ok, concrete class
Some people say that a pure virtual function is “a method which is declared by the base class, but for which no implementation is provided.” That statement is false.
You can provide an implementation for a pure virtual method in C++.
class Base {
public: Base() { f(); } virtual void f() = 0; }; class Derived : public Base { public: Derived() { f(); } virtual void f() { std::cout << “D”; }
int main(int, char **) {
Derived d; return 0;

Leave a Reply