1

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 {}?

1
  • 1. Foo has an implicitly declared copy constructor; 2. Foo obj(getFoo()) works too; 3. Same effect here. Commented Sep 13, 2018 at 1:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.