Skip to the page

Inheritance and polymorphism · core

Pure virtual functions and abstract classes

A pure virtual function, written = 0, must be overridden. A class with one is abstract: you cannot create it, only the classes that implement every pure virtual function. This is how C++ writes an interface.

The notes

What you must know

  • Pure virtual function: virtual double area() const = 0;. A class that has one, or inherits one without overriding it, is abstract.
  • You cannot create an object of an abstract class, but you can have pointers and references to it: Shape* s = new Circle(2);.
  • A derived class that does not override every pure virtual function is abstract too.
  • C++ has no interface keyword. An interface is a class with only pure virtual functions and a virtual destructor, and a class can inherit several of them.
  • An abstract class can have data members, constructors and normal functions. Its constructor runs when a derived object is created and sets the shared data, such as a colour.
  • A pure virtual function may still have a body, defined outside the class. A pure virtual destructor must have one, because it always runs when a derived object is destroyed.
  • Calling a pure virtual function virtually from the abstract class's constructor or destructor is undefined behaviour.
  • Shape design: Shape is abstract with a colour member and a pure virtual area(); Circle and Rectangle override area(); Printable is a separate interface that unrelated classes, such as Report, can also inherit.

The red pen

Common traps: mistake → fix

  • Mistake: An abstract class cannot have a constructor

    Fix: it can, and it runs for every derived object.

  • Mistake: A pure virtual function can never have a body

    Fix: it can, and a pure virtual destructor must.

  • Mistake: C++ has an interface keyword

    Fix: it uses a class with only pure virtual functions.

  • Mistake: You cannot have a pointer to an abstract class

    Fix: pointers and references are allowed.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a pure virtual function? What is an abstract class?
  2. How do you make an interface in C++?
  3. Shape: abstract class or interface? What if some shapes must also be printable?
  4. Can an abstract class have a constructor? Why would it?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview