Virtual functions are dynamically bound, but default parameter values are statically bound. This make redefining an inherited function’s default parameter a really bad idea. Let’s see an example
1 | class Shape { |
The symptom of the problem is similar to the one described in item 36. It’s unpredictable behavior depend on how draw
is called.
1 | Shape *pc = new Circle; |
pr-draw()
calls the correct function through dynamic binding but uses the default parameter from base class due to static binding.
Someone may think that this rule says never redefine inherited default parameter, what if I redefine it but make them the same? Like following?
1 | class Shape { |
Yeah of course you can do that but you just deferred the problem to the future, what if someone change just one place instead of all? So the correct thing to do it never redefine it.
One way to prevent derived class redefining it is using NVI idiom mentioned in item 35
1 | class Shape { |