Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why derived class function argument takes value of base class function argument?

I'm working on C++. Following is my code:

#include <iostream>
using namespace std;
class base
{
        public:
        virtual void display(int a = 4)
        {
                cout << "base ::  "<<  a*a << endl;
        }
};

class derived : public base
{
        public:
        void display(int b = 5)
        {
                cout << " Derived :: " << b*b*b <<  endl;
        }
};

int main()
{
        base *bobj;
        derived dobj;
        bobj = &dobj;
        bobj->display();
        return 0;
}

The output is:

Derived :: 64

The function of Base class is called, but default value of the parameter of derived function is used. Why the derived class method display(), takes the base class method argument value?

like image 447
BSalunke Avatar asked Sep 03 '12 09:09

BSalunke


1 Answers

Because you're calling it through a pointer to base. That's how it works.

Arguments are pushed on the argument stack (or inside registers) before the actual call. Because you have a pointer to base and no parameters, the default 4 is passed to the function. Then the correct function is called (derived::display), but with base's default parameter. Of course, this is an implementation detail, but the behavior is standard.

C++03 8.4/10

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.

I would provide emphasis on the quote, but the whole thing is pretty self-explanatory.

dobj.display();

would print 125 (5^3).

like image 66
Luchian Grigore Avatar answered Sep 23 '22 05:09

Luchian Grigore