user10355996
user10355996

Reputation: 11

struct initialization using curly brackets

Saw some codes like below in a C++ project:

struct Foo{ 
    std::wstring x; 
    //blah
}

// this func returns a Foo object 

Foo getFoo(){ 
    //blah 
}

void main() { 
    Foo obj{getFoo()}; //why can initialize by another Foo object in {}? 
}

{} is list-initialization. But no Foo arguments are listed here. Why does this work? Does struct have default copy constructor?

And does Foo obj(getFoo()) work? Any difference from the way of using {}?

Upvotes: 1

Views: 1592

Answers (1)

Dr. Watson
Dr. Watson

Reputation: 136

This is copy initialization. It calls the implicitly declared copy-constructor. Sources: https://en.cppreference.com/w/cpp/language/copy_initialization, https://en.cppreference.com/w/cpp/language/copy_constructor

Upvotes: 1

Related Questions