Saturday, 7 July 2018

Default arguments and virtual function

#include
using namespace std;
 
class Base
{
public:
    virtual void fun ( int x = 0 )
    {
        cout << "Base::fun(), x = " << x << endl;
    }
};
 
class Derived : public Base
{
public:
    virtual void fun ( int x )
    {
        cout << "Derived::fun(), x = " << x << endl;
    }
};
 
 
int main()
{
    Derived d1;
    Base *bp = &d1;
    bp->fun(); // Derived: fun(), x = 0;

    d1.fun(); // Derived: fun(), x = 10;
    return 0;
}
Default arguments do not participate in signature of functions. So signatures of fun() in base class and derived class are considered same, hence the fun() of base class is overridden. Also, the default value is used at compile time. When compiler sees that an argument is missing in a function call, it substitutes the default value given.

No comments:

Post a Comment