0

I just want to ask what is the difference in using const Type& name = object.getValue() and const Type name = object.getValue(), where Object::getValue() do not return a reference, but value. Both cases look to work in the excatly same way.

An example:

#include <iostream>

class Tmp {
 private:
  int x;
 
 public:
  Tmp(int x) : x{x} {}
  
  int getX() const { return x; }
  void setX(int x) { this->x = x; }
  
  friend std::ostream& operator<<(std::ostream& os, const Tmp& tmp) { os << tmp.x; }
};

int main() {
  Tmp ob { 1 };
  const int& x { ob.getX() };
  ob.setX(2);

  std::cout << "x=" << x << ", ob=" << ob;

  return 0;
}

Output:

x=1, ob=2

There are no difference if instead of const int& x { ob.getX() }; I simply use const int x { ob.getX() };. However, one difference which I can see is, if I do not add keyword const:

...
int& x { ob.getX() };
...

Then during compilation I receive:

main.cpp:26:22: error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
   int& x { ob.getX() };
                      ^

My main question is - is there any difference between const int& x { ob.getX() }; and const int x { ob.getX() }; (in this case, where Tmp::getX() returns value)?

Is there any rational use for such initialization?

const int& value = 6;

If not, then why there are no restrictions or warnings for that cases?

Glaz92
  • 17
  • 1

0 Answers0