I have a class Literal which is really just a wrapper for (const int). I want to have a second class PositiveLiteral which inherits from Literal, but has a constructor that asserts that its value is positive.
class Literal {
public:
Literal(int x):x(x){}
virtual ~Literal(){}
// Other methods
private:
const int x;
}
class PositiveLiteral : public Literal {
public:
PositiveLiteral(int x):Literal(x) {
assert(x > 0)
}
}
In this way, functions that expect a positive literal can simply take a PositiveLiteral as an argument. Then I don't need to put explicit assertions in my code and furthermore, where those assertions would fail, I can immediately see why.
I don't expect to otherwise inherit from Literal except for in this one case. Yet, because there is inheritance, I have to give Literal a virtual destructor to avoid undefined behavior which seems silly because PositiveLiteral has no exra information associated to it that Literal does not have. It's just a way to maintain an assertion without having to make it explicit.
What's another way to accomplish the same task without the need for a virtual method in what's supposed to be a simple wrapper class?