Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function member return

Tags:

c++

I am currently learning the basics of C++ and I have found the following code:

#include <iostream>
using namespace std;

class MyClass {
    int x;
public:
    MyClass(int val) : x(val) {}
    int& get() {return x;}
};

int main() {
  MyClass foo (10);
  foo.get() = 15;  
  cout << foo.get() << '\n';

  return 0;  
}

I don't understand why the line foo.get() = 15 works. To me it looks like a get and set at the same time. I guess it works due to the return type being int& and not only int.

Can someone explain to me how it works?

Thanks.

like image 808
Scipion Avatar asked Aug 26 '26 10:08

Scipion


2 Answers

Your foo.get is returning a reference to an int (noted int&).

References can be assigned (so they are l-values). Read the wikipage on C++ references, it is explaining better than I have time to. Or read carefully a good C++ programming book, like e.g. Stroustrup's Programming : Principles and Practice Using C++ or a Tour of C++ or The C++ Programming Language (or all of them!)

As Neil Kirk commented, you could nearly see references as a pointer implicitly dereferenced. In other words, and if you are familiar with C, think of int* get() { return &x; } and *foo.get() = 15;

See also this reference vs. pointer question

like image 58
Basile Starynkevitch Avatar answered Aug 28 '26 23:08

Basile Starynkevitch


The line works because the function is returning a reference, that's semantically equivalent to:

  int* get() {return &x;}

and:

  *foo.get() = 15;
like image 45
Paul Evans Avatar answered Aug 28 '26 22:08

Paul Evans