May 15, 2013

What's the output?

I've been recently doing C++ tests on the internet. I'm usually quite good at these but with something as complicated as C++, you'll always come across a new detail of the language that surprises you. In my case it was the following code:

#include <iostream>

struct B
  virtual int shift(int n = 2) const { return n << 2; }

struct D : public B
  int shift(int n = 3) const { return n << 3; }

int main()
  const D d;
  const B *b = &d;
  std::cout << b->shift() << std::endl;
  return 0;

What's the output?
Well, it turns out that while virtual invocations are evaluated at runtime, default arguments are assigned at compile time. If you think of it from a compiler programmer point of view it makes sense but for the user it's, in my opinion, completely counter-intuitive.

No comments:

Post a Comment