devxlogo

Default Arguments in Virtual Functions Must be Identical

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist