virtual function default arguments behaviour

Viewed 4898

I have a strange situation over the following code. Please help me to get it clarified.

class B
{
       public:
            B();
            virtual void print(int data=10)
            {
                  cout << endl << "B--data=" << data;
            }
};
class D:public B
{
       public:
            D();
            void print(int data=20)
            {
                  cout << endl << "D--data=" << data;
            }
};

int main()
{
     B *bp = new D();
     bp->print();
return 0;
}

Regarding the output I expected

[ D--data=20 ]

But in practical it is

[ D--data=10 ]

Please help. It may seem obvious for you but I am not aware of the internal mechanism.

7 Answers

Basically, what happens when you declare a function with a default argument like this is that you're (implicitly) declaring and defining an inline overload with one fewer argument that just calls the full function with that argument value. The thing is, this extra overloaded function is not virtual, even if the function is. So the function you've defined in B is equivalent to:

        virtual void print(int data)
        {
              cout << endl << "B--data=" << data;
        }
        void print() { print(10); }

what this means is that when you call print() (with no argument) the function you get is based on the static type (B in the case you find confusing). That then calls print(int) which is virtual, so uses the dynamic type.

If you want this default argument to be virtual, you need to explicitly define the overloaded function (as virtual) to make it work.

Related