Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it legal in C++ to call a constructor of a primitive type?

Why is the following code legal in C++?

bool a(false);

I mean, the T a(VALUE) should call constructor, right? I suppose it's not parsed as function declaration. But bool is plain type, it doesn't have constructor. Or does it?

I'm using Visual Studio 2012 if it's relevant.

like image 913
graywolf Avatar asked Jul 31 '15 13:07

graywolf


2 Answers

Although bool is a primitive type, and as such has no constructor, language designers introduced unified initialization syntax that works for primitives as well as for classes. This greatly simplifies writing template code, because you can continue using the

T tVar(initialVal);

syntax without knowing if T, a template type parameter, is primitive or not. This is a very significant benefit to template designers, because they no longer need to think about template type parameters in terms of primitive vs. classes.

like image 146
Sergey Kalinichenko Avatar answered Sep 23 '22 20:09

Sergey Kalinichenko


That is just a valid syntax to initialize POD types and have a similar behavior to a constructor (or even a copy constructor for that matter).

For example, the following would be valid:

bool a(false);
bool b(a);
bool c = bool(); // initializes to false

One interesting thing to note is that in

int main(int argc, const char *argv[])
{
  bool f();
  return 0;
}

f is a function declaration!

like image 28
Vincenzo Pii Avatar answered Sep 22 '22 20:09

Vincenzo Pii