Most Vexing Parse

The term “most vexing parse” was first used by Scott Meyers in his 2001 book Effective STL.

1. Introduction

The “most vexing parse” is a famous ambiguity in C++ syntax. It occurs when the compiler interprets a statement as function declaration instead of an object construction.

1
2
3
4
5
6
7
8
9
10
#include <iostream>

struct MyClass {
MyClass() { std::cout << "Constructor called!\n"; }
};

int main() {
MyClass obj(); // This looks like it creates an object, but it is not.
return 0;
}

Some compilers provide warnings that can help catch potential most vexing parse issues using -Wvexing-parse. The above code will generate compile warnings if this option is enabled.

1
2
3
4
5
<source>:8:16: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
MyClass obj();
^~
<source>:8:16: note: remove parentheses to declare a variable
MyClass obj();

C++ grammar allows declarations to look very similar to expressions. When the compiler encounters MyClass obj();, it prioritizes interpreting it as a declaration (because declarations are more fundamental in the language’s parsing rules) rather than an expression creating an object.

Another common example when using std::vector

1
2
std::vector<int> v(10, 20); // Correct: Creates a vector with 10 elements of value 20
std::vector<int> v2(); // Most Vexing Parse! Declares a function v2 returning a vector<int>

2. How to fix?

1
2
3
4
MyClass obj{}; // Use uniform initialization with braces (C++11 and later):
MyClass obj;
MyClass obj = MyClass();
MyClass* obj = new MyClass();

References

Author

Joe Chu

Posted on

2025-02-25

Updated on

2025-02-25

Licensed under

Comments