why default constructor is not available by default in some case
class foo {
public:
int a;
int b;
foo(int a_, int b_) : a(a_), b(b_) {}
};
int main() {
foo f;
}
when I try to compile the above code snippet, I got error message as below:
foo.cc: In function 'int main()'
foo.cc:12: error: no matching function for call to 'main()::foo::foo()'
foo.cc:10: note: candidates are: main()::foo::foo(int, int)
foo.cc:6: note: main()::foo::foo(const main()::foo&)
but if I comment the file of explicit constructor with two integer prarmeters, then the code can be compiled. I guess the rule behind the magic is that when you explicite declare constructor with parameters, c++ compilor will not atuomatically generate a default constructor with no parameters for yo开发者_如何学JAVAu.
Am I right? If am right, why does c++ has such behaviour? thanks in advance.
Compiler generates default constructor only if there're no user defined constructors.
C++ Standard 12.1/5:
A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a default constructor is implicitly declared.
Yes, you are right. If you declare a constructor it doesn't declare any implicit ones. As for why, I'm unsure.
class foo {
public:
foo(int a_ = 0, int b_ = 0) : a(a_), b(b_) {}
int a;
int b;
};
The C language only generates a default ctor if you do not specify one yourself. You could specify default arguments to your ctor though
Basically, if you don't have an explicit constructor, C++ tries to be compatible with C structs and other plain old data types by supplying a default constructor, so that its objects can be defined and used normally. But if you do have an explicit constructor, C++ no longer provides this default, since you should be in complete control of how objects of your classes can be used (like, how they should be constructed). So, if you don't specify a default constructor, you can have objects that are not constructible without parameters, which is often useful.
精彩评论