4 ms·
My favorite is similar thing, but in C++ and much more confusing: class Bar {}; class Foo { public: Foo(const Bar &c) { } void method() { } };
by seba_dos1 11y ago
My favorite is similar thing, but in C++ and much more confusing:
class Bar {};
class Foo {
public:
Foo(const Bar &c) { }
void method() { }
};
int main() {
Foo foo(Bar());
foo.method();
return 0;
}
"foo.method();" doesn't compile because:
error: request for member ‘method’ in ‘foo’, which is of non-class type ‘Foo(Bar (*)())’
That's right: "foo" is a declared function that returns instance of Foo and takes one argument - a function that returns instance of Bar :) But when you add additional parentheses in a line above:
Foo foo((Bar()));
then "foo" is an instance of Foo created by passing a new instance of Bar to its constructor, which is more like what you'd expect by reading the code, and the code compiles. Fun!
- BudVVeezer 11y agoYes, the most vexing parse. https://en.wikipedia.org/wiki/Most_vexing_parse https://en.wikipedia.org/wiki/Most_vexing_parse
- tylorr 11y agoI believe this situation is usually referred to as the "Most vexing parse".
- bobbyi_settv 11y agoC++11 initialization syntax solves this https://en.wikipedia.org/wiki/Most_vexing_parse#Uniform_initialization_syntax https://en.wikipedia.org/wiki/Most_vexing_parse#Uniform_init...