Search code examples
c++most-vexing-parse

Why do anonymous objects sometimes require a default constructor?


If I write the following program, it works as I expect:

struct Foo {
    Foo (std::string x) { std::cout << x << std::endl; }
};

int main () { Foo("hello, world"); }

However, if I write a slightly different program, I get a compilation error:

struct Foo {
    Foo (std::string x) { std::cout << x << std::endl; }
};

std::string x("hello, world");

int main () { Foo(x); }

The error is:

prog.cc: In function 'int main()':
prog.cc:10:20: error: no matching function for call to 'Foo::Foo()'

The complete error can be seen on IDEONE.

Why does the error occur for the second program and not the first?


Solution

  • You have declared a variable x with type Foo

    struct Foo {
        Foo(){}
        Foo (std::string x) { std::cout << x << std::endl; }
        void test(){ std::cout << "test" << std::endl; };
    };
    
    std::string x("hello, world");
    
    int main () { Foo(x); x.test(); }
    

    print "test"


    What you want is use uniform initialization syntax Foo{x}

    struct Foo {
        Foo (std::string x) { std::cout << x << std::endl; }
    };
    
    std::string x("hello, world");
    
    int main () { Foo{x}; }
    

    print "hello, world"