Virtual Function Defaults

Here’s a pitfall I wandered into earlier: virtual default values are not inherited from a base class! You’ll need to specify the default value again in the inherited class.

Since both our base class and default class can have default values, that leads to the next question – how do I know which default value will be used?

Whether the base class or derived class default value is used depends on the static type of the function call. What that means in plain English: If your function is called through a base class object/pointer/reference, you will use the default value in the base class. If you call through the derived class object/pointer/reference, you will use the derived default value.

From the C++ Standard

8.3.6.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.

Using C++ Without the Heap

Want to use C++, but worried about how much it relies on dynamic memory allocations? Our course provides a hands-on approach for learning a diverse set of patterns, tools, and techniques for writing C++ code that never uses the heap.

Learn More on the Course Page

Migrating from C to C++ Articles

Share Your Thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.