oops · high
Abstract Classes, Pure Virtual & Interfaces
Pure virtual functions, abstract classes you can't instantiate, and the C++ idiom for an interface (all pure virtual methods plus a virtual destructor) — what makes a class abstract, what a derived class must do to become concrete, and how abstract classes differ from pure interfaces.
A pure virtual (`= 0`) makes a class ABSTRACT — it can't be instantiated, only used via base pointer/reference. A derived class becomes concrete only when it overrides every pure virtual. An 'interface' is an abstract class that is all pure virtuals + a virtual destructor.
The code
struct Drawable { // an interface virtual void draw() const = 0; // pure virtual -> abstract virtual ~Drawable() = default; // always: virtual dtor};
struct Button : Drawable { void draw() const override { /* render */ } // must override};
// Drawable d; // ERROR: cannot instantiate abstractDrawable* p = new Button; // OK: use via base pointer / referencep->draw(); // dynamic dispatch -> Button::drawWhat this lesson walks through
- 01A pure virtual makes the class ABSTRACT
- 02A concrete class overrides every pure virtual
- 03Interface = all pure virtual + virtual dtor; use via base
Writing = 0 after a virtual function makes it pure virtual and its class abstract. You cannot create a Drawable object — it only defines an interface for derived classes to fulfil.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Abstract Classes, Pure Virtual & Interfaces and 100+ animated C++ interview lessons.