hally9k
hally9k

Reputation: 2583

Whats the difference between a 'non-virtual interface' and an 'abstract interface'?

I am implementing design patterns in C++ and I want my classes to utilise the interfaces via composition, this has lead me to study the different ways to implement interfaces. I would like to clarify the definitions of this terminology.

Upvotes: 4

Views: 884

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477444

A non-virtual interface is a public member function that's not virtual, but usually expected to be implemented in terms of a virtual function which is overridable:

class Interface
{
public:
    int compute()
    {
        return compute_impl();
    }
private:
    virtual int compute_impl() = 0;
protected:
    virtual ~Interface() { }
};

The neat thing here is that the implementation is actually private, since you can still override private methods - you just can't call them from the outside.

By contrast, an abstract interface is itself virtual, and purely so in the interface class:

class Interface
{
public:
    virtual int compute() = 0;
protected:
    virtual ~Interface() { }
};

While the two approaches look superficially similar, the advantage of the non-virtual interface idiom is that the interface is not encumbered with the implementation detail of virtual member functions. In other words, the fact that different implementations of the interface satisfy its contract by overriding a virtual functions is a detail of the implementation that is not part of the public aspect of the interface. In particular, the author is free to change the way the function is implemented in the future without having to worry about users having developed their own inheritance and override hierarchies.

Upvotes: 6

Related Questions