Default argument to virtual function.

Hey Guys
Can someone please advise what the rule is regarding default arguments used in virtual functions?
From the output of the code below, you can see the derived class function stuff() being called; however it prints 5 and not 10.

Regards
Rajat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

class A
{
    public:
        virtual void stuff(int i = 5) { cout << "A" << i << endl; }
};

class B : public A
{
    public:
        virtual void stuff(int i = 10) { cout << "B" << i << endl; }
};

int main(int argc, char *argv[])
{
    A *a = new B();
    a->stuff();
    return 0;
}


Output is:
B5
I believe that, according to the standard, the default parameters that are used are according to the static pointer type you are using (e.g. no dynamic binding). So since you have a pointer to A, it uses the default parameter of 5.
@Zhuge is correct. To give the actual reference, this is ยง8.3.6[dcl.fct.default]/10

ISO 14882 wrote:
A virtual function call uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.
Last edited on
Thanks much guys. I understand now.
Topic archived. No new replies allowed.