Definition or a declaration?

The C++ language is a context sensitive language, which means a compiler cannot always decide the semantics of a line of code in isolation. Sometimes, though, it is impossible for the compiler to make up it’s mind so it just guesses. Yup, that’s right, it guesses. To find out more try this little quiz.

Question: Is the following a definition or a declaration?

Answer: It could be either!

Why?

More specifically, it could be either a function declaration or an object definition:

  1. A declaration of a function that takes type Bar and returns type Foo
  2. A definition of f as a type Foo, which has a constructor that takes type Bar.

The problem is the syntax for both is identical so to resolve this problem the C++ standard states that a compiler must prefer function declarations to object definitions where it is unable to make a distinction! This can make for some rather entertaining compile time errors when you think you are creating an instance of an object and the compiler is convinced you are declaring a function.