Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual function with default argument, weird output

The output of this code is 15 and I really don't know why. I think that it uses x=5 in the foo function but I don't know why. Can anyone help me ?

#include <iostream>
#include <string>

using namespace std;


struct A
{
    virtual int foo(int x = 5)
    {
        return x*2;
    }
};

struct B : public A
{
    int foo(int x = 10)
    {
        return x*3;
    }
};



int main(int argc, char** argv)
{
  A* a = new B;
  cout << a->foo();
  return 0;
}
like image 291
DobreMihaela Avatar asked Jul 09 '26 23:07

DobreMihaela


1 Answers

I think that it uses x=5 in the foo function but I don't know why.

Yes, the default argument from the base class A's declaration (i.e. 5) is used here, because you're calling foo() on an object with static type A*. The default arguments are decided based on the static type, other than the dynamic type.

The standard has a clear explanation about this, $8.3.6/10 Default arguments [dcl.fct.default]:

(emphasis mine)

A virtual function call ([class.virtual]) 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. [ Example:

struct A {
  virtual void f(int a = 7);
};
struct B : public A {
  void f(int a);
};
void m() {
  B* pb = new B;
  A* pa = pb;
  pa->f();          // OK, calls pa->B::f(7)
  pb->f();          // error: wrong number of arguments for B::f()
}

— end example ]

like image 129
songyuanyao Avatar answered Jul 11 '26 14:07

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!