简体   繁体   中英

C++ Why do 3 of these constructor calls work, but one doesn't?

I have the following imbecile program:

#include <iostream>
using namespace std;

class Baz {
public:
    Baz() {cout << "Baz ctor " << endl;}
    Baz(int i) : Baz() {}
    ~Baz() {cout << "Baz dtor " << endl;}
};

int main() 
{
    cout << "w" << endl;
    Baz w;

    cout << "x" << endl;
    Baz x();

    cout << "y" << endl;
    Baz y(1);

    cout << "z" << endl;
    Baz z = Baz();

    return 0;
}

This produces the following output:

w
Baz ctor 
x
y
Baz ctor 
z
Baz ctor 
Baz dtor 
Baz dtor 
Baz dtor 

My question is thus: Why don't all these calls invoke the constructor?

I have been researching, but I have not found an explanation as to why the 2nd call does not invoke the constructor. I would expect Baz x() to be equivalent to Baz x = Baz() the same way that Baz y(1) would be equivalent to Baz y = Baz(1) , there must be something I'm missing.

Your statement Baz x(); declares x as a function with no parameters that returns a Baz . Change it to Baz x{}; or Baz x; to call the default constructor.

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