sdm@cs.brown.edu (Scott Meyers) (06/28/91)
Here's an interesting anomaly: a virtual function taking a default
parameter value can be redefined in a derived class with a different
default value. This can lead to unexpected behavior:
#include <iostream.h>
class Base {
public:
virtual void f(char * className = "Base") { cout << className << endl; }
};
class Derived: public Base {
public:
virtual void f(char * className = "Derived") { cout << className << endl; }
};
main()
{
Derived *d = new Derived;
d->f(); // prints "Derived"
Base *b = d;
b->f(); // prints "Base"
}
Both calls to f resolve to Derived::f, as expected, but the parameter has
different values, depending on which pointer was used to invoke it.
As I understand it, the reason that a default parameter value must be given
in the declaration xor the definition of a function is that that prevents
inconsistency between the two (ARM 8.2.6, pp. 144-5). Here we seem to have
a similar problem, except that it's between two declarations.
What would be the ramifications of prohibiting the specification of a
default value for a parameter in a redefinition of an inherited virtual
function, i.e., requiring that derived classes use the default parameter
values specified in the virtual functions they inherit?
Scott
-------------------------------------------------------------------------------
What do you say to a convicted felon in Providence? "Hello, Mr. Mayor."