Does it ever make sense to override a pure virtual method with another pure virtual method? Are there any functional differences or perhaps code style reasons to prefer one of the following options over the other?
class Interface {
public:
virtual int method() = 0;
};
class Abstract : public Interface {
public:
int method() override = 0;
};
class Implementation : public Abstract {
public:
int method() override { return 42; }
};
Versus:
class Interface {
public:
virtual int method() = 0;
};
class Abstract : public Interface {};
class Implementation : public Abstract {
public:
int method() override { return 42; }
};
Both codes produce the same effect: class Abstract
is abstract and you can't instantiate it.
There is however a semantic difference between the two forms:
Abstract
is abstract (just in case it's name would not be self-speaking enough ;-) ). Not only does it reminds it: it also ensures it by making sure that method is pure virtual. Abstract
inherits everything exactly from Interface
. It's abstract if and only if its base class is. This has consequences on future evolutions of your code. For instance, if one day you change your mind and want interface to have a default implementation for method()
:
Abstract
remains abstract and will not inherit the default implementation of the method. Abstract
would continue to inherit and behave exactly as Interface
. Personally I find that the second form is more intuitive and ensures better separation of concerns. But I can imagine that there could be some situations were the first form could really make sense.