0

while reading through vptr and vtable concept i got this wonderful piece of code, but i am not able to make out the concept involved here:

#include <iostream>
using namespace std;
class A
{
 public:
  virtual void foo(int x = 10)
  {
    cout << "base x : " << x << "\n";
  }
  virtual void bar()
  {
    cout << "base bar\n";
  } 
};
class B : public A  
   {
 public:
   virtual void foo(int x = 20)
   {
     cout << "derived x : " << x << "\n";
   }
  private:
   virtual void bar()
   {
     cout << "derived bar\n";
   }

   };
   class C : public B
   {

   };
   int main()
   {
     A x; x.foo(); // x.foo(10);
     B y; y.foo(); // x.foo(20);
     A *p(&y);
     p->foo(); 
   }

now the output i get here is:

base x : 10
derived x : 20
derived x : 10

how is it possible that even when derived x(i.e B::foo()) is being printed then the default argument is that of base function(i.e A::foo())?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Sumit Singh
  • 182
  • 3
  • 14

2 Answers2

1

It seems that the default parameters are resolved at compile time. See here and here.

The default values that are used will be those defined in the static (compile-time) type. So if you were to change the default parameters in an override, but you called the function through a base class pointer or reference, the default values in the base would be used.

Community
  • 1
  • 1
James Adkison
  • 9,412
  • 2
  • 29
  • 43
1

C++ standard section 8.3.6 point 10 mentions that:

A virtual function call (10.3) 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.

In your example the evaluation of default argument is done on the basis of type of "p" which is "A". Hence the evaluation of default argument is done from the declaration of A, and the calling of function happens by the usual lookup in vptr table.

bashrc
  • 4,725
  • 1
  • 22
  • 49
  • **evaluation of default argument is done on the basis of type of "p" which is "A". ** -- yes i can understand something about this concept thanks a lot. – Sumit Singh Mar 29 '15 at 15:43