skip to content

In C++, how does a Button class inherit from both Drawable and Clickable interfaces, and what makes it instantiable?

level: juniorimportance: should knowfreq 55%

answer

  1. abstract classes play the interface role
  2. one access specifier per base
  3. class-key class defaults to private
  4. override every pure virtual

basics

~10 s

List both bases, each with its own access specifier: class Button : public Drawable, public Clickable. Button stays abstract, and cannot be instantiated, until it overrides every pure virtual function inherited from both bases.

solid answer

~40 s

C++ has no `interface` keyword: an interface-style base is an abstract class with pure virtual functions, a virtual destructor and no data. A class inherits several of them by listing them, each with **its own** access specifier: `class Button : public Drawable, public Clickable`. Leave one off and the class-key decides, so in `class Button : public Drawable, Clickable` the `Clickable` base is **private** and code outside `Button` can no longer convert a `Button` to `Clickable&`. `Button` is abstract until it provides a final overrider for every pure virtual function of every base; `Button ok;` is rejected otherwise. If both bases declare the same virtual signature, one `override` in `Button` overrides both. Once complete, a `Button` binds to `Drawable&` and `Clickable&` alike.

code

cpp · 28 lines
cpp
#include <iostream>

struct Drawable {
    virtual ~Drawable() = default;
    virtual void draw() const = 0;
};

struct Clickable {
    virtual ~Clickable() = default;
    virtual void on_click(int x, int y) = 0;
};

class Button : public Drawable, public Clickable {
public:
    void draw() const override { std::cout << "draw button\n"; }
    void on_click(int x, int y) override {
        std::cout << "click at " << x << ',' << y << '\n';
    }
};

void render(const Drawable& d) { d.draw(); }
void dispatch(Clickable& c) { c.on_click(3, 4); }

int main() {
    Button ok;
    render(ok);     // Button -> Drawable&
    dispatch(ok);   // Button -> Clickable&
}

go deeper

for a junior

Write the declaration with an access specifier on every base and name the rule: the class stays abstract until every pure virtual from every base is overridden.

for a middle

Explain the default access by class-key, why a private base blocks conversion outside the class, and that one override can satisfy the same signature in both bases.

for a senior

Show the production habits: override on every implementation, virtual destructors on interfaces, no data in them, and using-declarations when non-virtual names collide.

for a principal

Connect the habits to a team rule that allows several interface-style bases but at most one base carrying state, and explain what that rule prevents.

## Interfaces in C++ are abstract classes C++ has no separate interface construct. What other code bases call an interface is, in C++, an **abstract class**: a class with at least one **pure virtual function** (declared with `= 0`). An *interface-style* base goes further by convention: every member function is pure virtual, it has no data members, and it declares a **virtual destructor** so that an object can be destroyed through a pointer to the interface. ```cpp struct Drawable { virtual ~Drawable() = default; virtual void draw() const = 0; }; ``` A GUI toolkit typically has several of these, one per capability: `Drawable` for anything that paints itself, `Clickable` for anything that reacts to the mouse. A `Button` is both, so it inherits from both. ## Listing several bases The **base-specifier-list** after the colon names every direct base, separated by commas. Each entry carries its own access specifier; there is no "the first `public` applies to the rest". | Declaration | Access of `Clickable` | |---|---| | `class Button : public Drawable, public Clickable` | public | | `class Button : public Drawable, Clickable` | **private** (class-key `class`) | | `struct Button : Drawable, Clickable` | public (class-key `struct`) | The standard says that, without an access specifier, `public` is assumed when the derived class is defined with `struct` and `private` when it is defined with `class`. A private base is an implementation detail of `Button`: code outside `Button` cannot convert a `Button` to `Clickable&`. Clang reports exactly that at the call site: `cannot cast 'Button' to its private base class 'Clickable'`. The same class may not appear twice as a *direct* base (`class Y : public X, public X` is ill-formed), but any number of distinct bases is allowed. ## Becoming instantiable A class that inherits a pure virtual function and does not override it is itself abstract. With two interfaces, `Button` must provide an overrider for **every** pure virtual function of **both** bases. Overriding only `draw()` leaves `on_click()` pure, and `Button ok;` fails to compile; Clang says `variable type 'Button' is an abstract class` and points at the unimplemented `on_click`. This is a compile-time check, not a run-time surprise. Good habits when implementing the interfaces: - Mark each implementation `override`, so a signature typo becomes a compile error instead of a new, unrelated function. - Keep the interfaces free of data members, so `Button` never inherits two copies of shared state. - Give each interface a virtual destructor, so `delete` through a `Drawable*` or a `Clickable*` runs `Button`'s destructor. ## One override, two bases If `Drawable` and `Clickable` both declare `virtual std::string id() const = 0;`, a single `std::string id() const override` in `Button` overrides **both**: a function declared in `Button` overrides every base virtual function with the same name, parameter list and qualifiers. Calling `id()` through a `Drawable&` or a `Clickable&` reaches the same function. Non-virtual members behave differently. If the two bases each declare a member function named `id`, even with different parameters, an unqualified `button.id()` is **ambiguous**: name lookup finds `id` in two base classes before overload resolution ever runs. A `using Drawable::id;` and `using Clickable::id;` pair in `Button` brings both into one overload set. ## Using the object through either interface Once `Button` is complete, it converts implicitly to a reference or pointer to either public base, so a renderer that takes `const Drawable&` and an input dispatcher that takes `Clickable&` can both accept the same object. Each function sees only its own interface. The run in the code example prints `draw button` and `click at 3,4`. ## Construction and destruction order The bases of `Button` are constructed in the order they appear in the base-specifier-list, `Drawable` first and `Clickable` second, whatever order a constructor's mem-initializer list names them in; with `-Wall`, Clang warns when the two orders disagree (`-Wreorder-ctor`). Members follow, then the constructor body. Destruction runs in exactly the reverse order. For data-free interfaces this rarely matters, but it becomes visible as soon as a base constructor logs, registers the object somewhere or reads a virtual function. ## Mistakes interviewers listen for 1. Assuming the access specifier of the first base carries over to the next one. 2. Believing a class with two interfaces is instantiable once one interface is implemented. 3. Writing two separate overrides, or qualified names, for a virtual signature both bases share. 4. Leaving the destructor of an interface non-virtual and then deleting through it. How the two base subobjects are laid out in memory, and what that means for pointer values, is a separate topic in this lesson.

  • Why should each interface-style base in C++ declare a virtual destructor?
    Code often owns a `Button` through one interface, for example `std::unique_ptr<Clickable>`. Deleting an object through a pointer to a base whose destructor is not virtual is undefined behaviour. With `virtual ~Clickable() = default;` the delete dispatches to `Button`'s destructor, which then destroys both base subobjects. A base that is never used for deletion may instead make its destructor protected and non-virtual.
  • In C++, Drawable declares a non-virtual id() and Clickable a non-virtual id(int); why does button.id() fail to compile?
    Name lookup for `id` in `Button` finds declarations in two different base classes, and the standard makes that lookup ambiguous before overload resolution looks at the parameters, so differing signatures do not help. Clang reports `member 'id' found in multiple base classes of different types`. Adding `using Drawable::id;` and `using Clickable::id;` to `Button` merges both into one overload set, or a caller can qualify `button.Drawable::id()`.

  • One public before the first base makes every listed base public.
  • Implementing one interface's pure virtuals is enough to instantiate the class.
  • Two bases with the same virtual signature need two separate overrides.
  • C++ needs a special keyword to declare an interface-style base.
  • Interface-style bases never need a virtual destructor.