Why the default constructor is not available by default

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 received an error message as shown 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 on the explicit constructor file with two integer prarmeters, then the code can be compiled. My guess is that the rule underlying magic is that when you explain to declare a constructor with parameters, the C ++ compiler will not automatically generate a default constructor without parameters for you.

I'm right? If correct, why does C ++ have this behavior? thanks in advance.

+3
source share
4 answers

, .

++ Standard 12.1/5:

X X, . , X, .

+9

, . , . .

+2
class foo {
public:
    foo(int a_ = 0, int b_ = 0) : a(a_), b(b_) {}
    int a;
    int b;
};

C ctor , . ctor,

+1

, , ++ C- , , . , ++ , , (, ). , , , , .

+1

Source: https://habr.com/ru/post/1752761/


All Articles