🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

1 total messages Started by Scott Meyers Fri, 28 Jun 1991 15:47
Virtual Functions and Default Parameter Values
#1345
Author: Scott Meyers
Date: Fri, 28 Jun 1991 15:47
43 lines
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."
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads