简体   繁体   中英

Different ways to use default argument to a constructor in C++

What is the difference between the following three pieces of code with respect to MSVC?

Code 1: Foo ctor defined as:

Foo::Foo(Bar &bar = Bar());

Foo ctor used as:

Foo foo = new Foo();

Code 2: Foo ctor defined as:

Foo::Foo()
{
    Bar bar = Bar();
    Foo(bar);
}

Foo::Foo(Bar &bar);

Foo ctor used as:

Foo foo = new foo();

Code 3: Foo ctor defined as:

Foo::Foo(Bar &bar);

Foo ctor used as:

Bar bar = Bar();
Foo foo = new foo(bar);

Edit: Made corrections to the code. The intention was to explain the idea, didn't focus on the code, so made the mistake. Sorry about that.

The question specifically is to figure out the difference between code 2 and 3. Due to some reason, in the case of Code 2, the consumer of the Foo class ctor results in a crash and in case of Code 3 it doesn't. I don't have the specific code of the consumer, so cannot figure it out myself.

In the first two, you are not even calling a constructor, you are declaring a function:

Foo foo(); // function foo, returns a Foo object

To default construct a Foo , you need

Foo foo;   // C++11 and C++03
Foo foo{}; // C++11

Most of your code is either illegal, or it doesn't do what you expect. For example, this constructor doesn't do anything other than create a local Bar variable bar , and an attempt to create an instance type Foo with the same name:

Foo::Foo()
{
    Bar bar = Bar(); // local variable bar
    Foo(bar);        // error: 'bar' has a previous declaration as 'Bar bar'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM