Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code executes derived class method, but gets default parameter from base class method

Can someone explain why the result of the code below would be "class B::1" ?

Why does the virtual method of derived class uses the default parameter of a base class and not his own? For me this is pretty strange. Thanks in advance!

Code:

#include <iostream>

using namespace std;

class A
{
public:
    virtual void func(int a = 1)
    {
        cout << "class A::" << a;
    }
};

class B : public A
{
public:
    virtual void func(int a = 2)
    {
        cout << "class B::" << a;
    }
};

int main()
{
    A * a = new B;
    a->func();

    return 0;
}
like image 831
Aremyst Avatar asked Jun 03 '12 15:06

Aremyst


2 Answers

Because default arguments are resolved according to the static type of this (ie, the type of the variable itself, like A& in A& a;).

Modifying your example slightly:

#include <iostream>

class A
{
public:
    virtual void func(int a = 1)
    {
        std::cout << "class A::" << a << "\n";
    }
};

class B : public A
{
public:
    virtual void func(int a = 2)
    {
        std::cout << "class B::" << a << "\n";
    }
};

void func(A& a) { a.func(); }

int main()
{
    B b;
    func(b);
    b.func();

    return 0;
}

We observe the following output:

class B::1
class B::2

In action at ideone.

It is not recommended that a virtual function change the default value for this reason. Unfortunately I don't know any compiler that warns on this construct.


The technical explication is that there are two ways of dealing with default argument:

  • create a new function to act as trampoline: void A::func() { func(1); }
  • add-in the missing argument at the call site a.func() => a.func(/*magic*/1)

If it were the former (and assuming that the A::func was declared virtual as well), then it would work like you expect. However the latter form was elected, either because issues with virtual were not foreseen at the time or because they were deemed inconsequential in face of the benefits (if any...).

like image 62
Matthieu M. Avatar answered Sep 30 '22 09:09

Matthieu M.


Because default value is substituted during compilation and is taken from declaration, while real function to be called (A::func or B::func) is determined at runtime.

like image 21
Ruben Avatar answered Sep 30 '22 09:09

Ruben