0

I have this code but compilation failed:

class TextBlock { public: TextBlock(std::string &s) { text = s; } private: std::string text; }; int main() { TextBlock tb("Hello"); std::cout<< tb[0] << std::endl ; } 

why when the constructor is TextBlock(const std::string &s) the above code can compile success ?

2
  • Temporary cannot bind to non-const (l-value) reference. Commented Sep 2, 2020 at 12:56
  • sloppy speaking you need a string somewhere, a reference is just a reference. If the reference is const then the function is fine with taking a temporary because anyhow it wont be modified. Passing a temporary to a function that expects a non-const reference is pointless because you cannot observe the modifications, hence it makes sense that this is an error Commented Sep 2, 2020 at 12:57

1 Answer 1

1

the constructor is specting a ref to a string do instead:

std::string x{"hello"}; TextBlock tb(x); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.