Virtual Function Defaults

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.


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.

More info: Guru of the week: Overriding Virtual Functions

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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