-1

I am trying to understand the useage of 'const' and '&' in the following function declaration. I know that the last 'const' means the function cannot change member variables in the class and that 'const std::string& message' means the variable passed to the function cannot be changed, but I don't understand the meaning of 'const Logger&'. What is the purpose of this first 'const' and why is there an '&' following 'Logger'? Is this function meant to return an address or a pointer?

const Logger& log(const std::string& message) const;
Marco Aiello
  • 179
  • 10
  • 5
    Do you understand the purpose of `&` in `const std::string& message`? It works the same way for the return type. – François Andrieux Dec 08 '21 at 15:19
  • 4
    This function returns a const reference. Compilers may implement references as pointers, but not necessarily. https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in?rq=1 – JohnFilleau Dec 08 '21 at 15:19
  • 3
    The function is returning "A const reference to a `Logger`". Your question seems to be ["What is a reference?"](https://stackoverflow.com/questions/2765999/what-is-a-reference-variable-in-c) – Drew Dormann Dec 08 '21 at 15:19
  • 4
    `log` says "Here's a `Logger` reference. It's the actual `Logger`, not a copy. You're not allowed to change it." – JohnFilleau Dec 08 '21 at 15:19
  • 1
    if you understand `const std::string&` then you also understand `const Logger&`. One is the argument type the other is the return type – 463035818_is_not_an_ai Dec 08 '21 at 15:21
  • You also have to keep in mind that returning a ref to a local object/variable of the function will cause a dangling reference problem. And you should avoid that. In general, only return references when you are sure that the returned object has a longer lifetime than the called function's scope. – digito_evo Dec 08 '21 at 15:27

1 Answers1

2

So const Logger& is the return type of log. const means you will not be able to edit the return value at all. The return type Logger& means you'll get a reference to a Logger and not a copy of it.