0

My question is inspired from the comments on this SO post.

How exactly does string()+char, like string()+'a' work? Specifically:

  1. Is the string() constructor called for a nameless temporary object?
  2. What is the datatype of this object?
  3. Logically, how can I concatenate a char to this object to get a string?
P.K.
  • 379
  • 1
  • 4
  • 16
  • 1
    1) How the temporary object get constructed is implementation-defined. 2) `std::string`, of course, what else could it be? 3) The `+` operator already returns a `std::string`. Nothing else needs to be done in order to obtain a `std::string` out of this. – Sam Varshavchik May 06 '18 at 02:42
  • @SamVarshavchik, got it. Thanks! – P.K. May 06 '18 at 02:42

1 Answers1

1

Assuming you are using the std::string implementation, a quick look the relevant functions in the C++ reference can help you understand this behaviour.

  1. Is the string() constructor called for a nameless temporary object?
  2. What is the datatype of this object?

Calling the constructor string() with no arguments

Constructs an empty string, with a length of zero characters.

therefore the datatype of the given object will be of type std::string.

  1. Logically, how can I concatenate a char to this object to get a string?

You concatenate as if you would to any string, trough the + operator, which is overloaded to work with a string object as the left hand side operand, and a character as the right hand one.

Aleon
  • 311
  • 2
  • 10