It depends on the design of the base class. Suppose you have a base class
class Stream { public: virtual bool canSeek() = 0; virtual void seek(int offset) = 0; };
Note. This example comes from the .NET world, where the Stream
class library class does have such a CanSeek
virtual property. I do not want to discuss whether this is a good design, as I can see valid arguments for both sides. It is enough that such base classes exist in reality.
Now the derived class can indicate that
class SpecificStream final : Stream { private: virtual bool canSeek() { return false; } virtual void seek(int offset) { throw "no seek for you"; } }
In this derived class, the fact that seek
implemented in general is that it is technically necessary. However, any code that deals with this SpecificStream
already knows that the seek
function is completely useless with this class and should not be called. When encoding with the Stream
base class, it may make sense to check the result of canSeek()
and call seek
only if the result was true. When coding with the SpecificStream
class, it makes no sense to check canSeek()
, since its result is statically known, and it definitely does not make sense to call seek()
. If such calls are a programmer error, it makes sense to help the compiler provide useful messages for such calls.
source share