Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
Sep 28, 1998

Default Arguments in Virtual Functions Must be Identical

You should pay attention when using default arguments in virtual functions. The default values in the overriding function have to be identical to the corresponding default values in the base class. Otherwise, unexpected results may occur:
class Base {
public: virtual void say (int n = 0) const { cout<say();  //output is 0 and not 5!
It should be noted that unlike virtual functions, which are resolved at run time, default arguments are resolved statically, that is, at compiled time. In the example above, the static type of p is "pointer to Base". The compiler therefore supplies 0 as a default argument in a function call. However, the dynamic type of p is "pointer to Derived", which takes 5 as a default argument.

Since a base class and a derived class may be compiled separately, most compilers cannot detect such inconsistencies. Therefore, the programmer is responsible for making sure that the default values of a virtual function in all levels of derivation match exactly.

Danny Kalev
Thanks for your registration, follow us on our social networks to keep up-to-date