In my example I declared a class Player1. The constructor expects a read-only input and handles it as reference. Thats okay.
class Player1 {
private:
  std::string m_Name;
public:
  Player1(const std::string &name) : m_Name(name) {}
  std::string GetName() { return m_Name; }
};
For instanciation either way (A) is possible:
 std::string aName = "Chris"; //declare string-variable and assining value
  Player1 chris(aName); //passing the variable to the constructor which handles it as reference
Or the way (B) is possible:
Player1 chris("Chris"); //direct text input
I dont get why the way B direct text input is okay for the compiler. From my point of view the constructor only accepts a reference, which is for me a pre-declared/assigned variable.
Player1(const std::string &name)
The only explanation for me is that the constructor internally creates a variable which is handled as reference.
Does somebody have some clear words as an enlightment? I know its a rather small parts question. One could also say, well it works.
Your tentative explanation is actually pretty close, but it differs in a couple of details from what actually happens. It's not the constructor that does any work here, the constructor still takes a const std::string & as a parameter. That part doesn't change, and nothing exceptional happens in the constructor, in this case.
It's the call site, where the constructor gets called (where the object gets constructed), is where the conversion happens. At the call site the string literal, which is a const char [6] gets used to construct a temporary std::string object. A const char [n] decays to a const char * when passed to a function or a method (such as a constructor). A std::string has a constructor that accepts a const char * as a parameter. So this boils down to a temporary std::string that gets constructed at the call site.
Then, the next domino falls, and a reference to the std::string gets passed to your object's constructor. That's another one of C++ rules: a temporary object can bind to a const reference.
Finally, after your Player gets constructed, the temporary std::string object gets destroyed.
All of the above steps are governed by a long, long list of various C++ rules that specify how implicit type conversions and constructors work, and are actually a somewhat of a simplification. But that's what's effectively happens, in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With