Thursday, May 15, 2008

C++ tidbit - virtual functions and default arguments

Virtual functions are bound dynamically where as default arguments are bound statically

class Base {
public:
virtual void func( int x = 10 ) {
_x = x;
std::cout << _x;
};

private:
int _x;
};

class Derived: public Base {
public:
virtual void func( int x = 20 ) {
_x = x;
std::cout << _x;
};

private:
int _x;
};

int main()
{
Base *b = new Base();
std::cout << "Default Value in Base: ";
b->func();
std::cout << std::endl;

Base *d = new Derived();
std::cout << "Default Value in Derived: ";
d->func();
std::cout << std::endl;

return 0;
}

Output:

Default Value in Base: 10
Default Value in Derived: 10

Default arguments of virtual methods in the base gets statically bound (in our case Base::func() ), hence never override the default values in derived virtual methods, doing so might confuse us with derived object's default behavior.

No comments: