Article View: comp.std.c++
Article #1345Virtual Functions and Default Parameter Values
From: Scott Meyers
Date: Fri, 28 Jun 1991 15:47
Date: Fri, 28 Jun 1991 15:47
43 lines
1958 bytes
1958 bytes
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."
Technical Details
Message-ID:
<79633@brunix.UUCP>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!decwrl!uunet!brunix!sdmShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!decwrl!uunet!brunix!sdm From: sdm@cs.brown.edu (Scott Meyers) Newsgroups: comp.std.c++ Subject: Virtual Functions and Default Parameter Values Message-ID: <79633@brunix.UUCP> Date: 28 Jun 91 15:47:17 GMT Sender: news@brunix.UUCP Reply-To: sdm@cs.brown.edu (Scott Meyers) Organization: Brown University Department of Computer Science Lines: 43