Virtual functions and default parameter arguments are a staple of all C++ programmers, but you might get more than you bargained for if you decide to mix and match them. Try this little quiz and see if your coders intuition is correct.
Question: Without using a compiler, what is the value of X?
struct Foo { virtual size_t func(size_t st = 0) const = 0; }; struct Bar : Foo { virtual size_t func(size_t st = 999) const { return st; } }; int main() { Foo const & foo = Bar(); size_t const X = foo.func(); // What value does X have? }
Answer: It will be set to 0 and not, as you’d expect, 999.
Why?
The reason for this is because default parameters are always bound to the static and NOT dynamic type. This can be a very hard to track down source of defects so be very careful when mixing and match default parameters with virtual functions as you might just get more than you bargained for.