c++/10311: Wrong default argument used in virtual function call

nathansmith_2003@yahoo.com nathansmith_2003@yahoo.com
Fri Apr 4 16:36:00 GMT 2003


>Number:         10311
>Category:       c++
>Synopsis:       Wrong default argument used in virtual function call
>Confidential:   no
>Severity:       serious
>Priority:       medium
>Responsible:    unassigned
>State:          open
>Class:          sw-bug
>Submitter-Id:   net
>Arrival-Date:   Fri Apr 04 16:36:00 UTC 2003
>Closed-Date:
>Last-Modified:
>Originator:     nathansmith_2003@yahoo.com
>Release:        2.96,3.2.1
>Organization:
>Environment:
Linux
>Description:
The default argument of the pointer type's function is being used rather than the actual type when calling a virtual function with default arguments. i.e. if you have a class B derived from another class A, both with a virtual function print which accepts a char*, B::print will use A::print's default arguments when called, if the pointer to an instance of B is of type A*.

Section dcl.fct.default par 10A of the ANSI C++ spec states that "An overriding function in a derived class does not acquire default arguments from the function it overrides."

This bug is persistent even when -pedantic is specified.
>How-To-Repeat:
When executing the following code, one would expect the output to be "hi there" due to the default arguments of the virtual functions. However, the unexpected result of "hihi" is produced instead. 

#include <iostream>

class A {
public:
        virtual void print(const char *x = "hi");
};

void A::print(const char *x) { std::cout << x; }

class B : public A {
public:
        virtual void print(const char *x = " there");
};

void B::print(const char *x) { std::cout << x; }

int main(void)
{
        A *a = new A;
        A *b = new B;

        a->print();
        b->print();

        std::cout << std::endl;

        delete a;
        delete b;

        return 0;
}
>Fix:

>Release-Note:
>Audit-Trail:
>Unformatted:



More information about the Gcc-prs mailing list