2

I'm new to C++ and trying to understand something. I have this code in my main.cpp:

Radio r = Radio("PSR", 100.8);

or that code:

Radio r("PSR", 100.8);

Both seem to work and doing the same thing. So what's the difference?

Jason
  • 36,170
  • 5
  • 26
  • 60
  • details matter. `type name();` is a function declaration. In your actual code it isnt `name();` but `name(parameter)` – 463035818_is_not_an_ai May 30 '22 at 12:34
  • `type name()` is declaration and definition of the variable `name` of type `type` and call to the `type` constructor all at once, `type name = type()` is also declaration and definition of var `name`, but it is initialized by copy assignment of an anonymous instance of `type`, created with the `type()` constructor. Crystal clear, right? Well that's C++ for you... – joH1 May 30 '22 at 12:38
  • 5
    In the snippets provided, they both work and both do the same thing. Obligatory [The Nightmare of Initialization in C++](https://www.youtube.com/watch?v=7DTlWPgX6zs) by Nicolai Josuttis. An hour long presentation on the initialization syntax pain point in C++. – Eljay May 30 '22 at 12:41
  • @joH1 no. `type name()` does not declare a variable called `name` of type `type`. It declares a function: https://godbolt.org/z/Pe65q9r5o – 463035818_is_not_an_ai May 30 '22 at 12:44
  • 1
    In C++ there is about dozen ways to initialise something and sometimes the differences matter but sometimes not. It is made to keep it complicated as job security. – Öö Tiib May 30 '22 at 12:44
  • @ÖöTiib job security of book writers, right? ;) I didnt meet any mortal programmer who unstood all C++ initialization – 463035818_is_not_an_ai May 30 '22 at 12:45
  • @463035818_is_not_a_number indeed, sorry, I oversimplified the expressions for clarity, but too much (my C++ is a bit rusty) – joH1 May 30 '22 at 12:53

1 Answers1

6

Radio r = Radio("PSR", 100.8); is copy initialization while Radio r("PSR", 100.8); is direct initialization.

C++17

From C++17 due to mandatory copy elison both are the equivalent.

Radio r = Radio("PSR", 100.8); //from C++17 this is same as writing Radio r("PSR", 100.8);

Prior C++17

But prior to C++17, the first case Radio r = Radio("PSR", 100.8); may result in the creation of a temporary using which r is copy initialized. This is because prior to C++17, there was non-mandatory copy elison.


Another thing to note is that if you were to write:

type name(); //this is a function declaration

the above is a declaration for a function named name which has the return type of type and has 0 parameters.

Jason
  • 36,170
  • 5
  • 26
  • 60