Overriding the default parameter value inherited from a parent class will lead to unexpected results when the child class is referenced from a
pointer to the parent class.
Noncompliant code example
enum E_ShapeColor {E_RED, E_GREEN, E_BLUE};
class Shape
{
public:
virtual void draw(E_ShapeColor color = E_RED) const
{
...
}
};
class Rectangle : public Shape
{
public:
virtual void draw(E_ShapeColor color = E_BLUE) const override // Noncompliant
{
...
}
};
int main() {
Shape *shape = new Rectangle{};
shape->draw(); // unexpectedly calls Rectangle::draw(RED)
}
Compliant solution
enum E_ShapeColor {E_RED, E_GREEN, E_BLUE};
class Shape
{
public:
virtual void draw(E_ShapeColor color = E_RED) const
{
...
}
};
class Rectangle : public Shape
{
public:
virtual void draw(E_ShapeColor color) const override
// OR: virtual void draw(E_ShapeColor color = E_RED) const override
{
...
}
};
int main() {
Shape *shape = new Rectangle{};
shape->draw(); // expectedly calls Rectangle::draw(RED)
}