Domanda

Take the following class:

class Foo{
public:
    Foo(std::string bar_, int baz_ = 7)
    :bar(bar_)
    ,baz(baz_)
    {}

private:
    std::string bar;
    int baz;
};

Since Foo(std::string bar_, int baz_ = 7); is my only constructor, the compiler shouldn't implement a default constructor for me right? I would think that the only two ways I could construct this class are:

Foo foo("foo");  
//or  
Foo foo("foo",0);  
//plus copy constructor and overloaded assignment operator.

Yet, why is this possible?

int main(){

    Foo foo();
}

I don't understand how I can default construct a class when the only public constructor requires a value for its first parameter. Making the default constructor private or trying to C++11 delete it, makes no difference. How is this happening?
http://ideone.com/CL7IZo

È stato utile?

Soluzione

Because Foo foo(); is a forward declaration of a function which returns a Foo and takes no arguments. Use Foo foo; instead and you will get your error.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top