Returning an element of a C ++ function

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

#include <iostream>
using namespace std;

class MyClass {
    int x;
    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 works foo.get() = 15

. To me it feels like getting and installing at the same time. I think it works because of the return type int&

and not only int


Can someone explain to me how this works?



source to share

4 answers

Yours foo.get

returns a reference to int

(checked int&


Links can be assigned (which is why they are l-values). Read the wikipage on C ++ references , it explains better than I have time. Or read carefully a good C ++ Programming book like eg. Stroustrup Programming: Principles and Practice Using C ++ or the Tour of C ++ or the C ++ Programming Language (or all of them!)

As Neil Kirk commented, you could almost see the references as an implicitly dereferenced pointer. In other words, if you are familiar with C, think about int* get() { return &x; }

and*foo.get() = 15;

See also this link to question with index



The line works because the function returns a reference that is semantically equivalent:

  int* get() {return &x;}



  *foo.get() = 15;




In C ++, the return value from a function is a variable that is stored on the stack or heap, but without your name. so here

int& get() {return x;}


so foo.get () as one group (foo.get ()) returns a variable, in your case it is a reference variable which means that return (foo.get ()) is a variable x inside foo.

so foo.get () = 15 is the same as foo.x = 15 because it returns by reference.

Note: foo.x = 15 will give a compiler error as it is private by default, but it is very good to return it as a reference to access it.



The code is written in full. You are returning a non-persistent reference to the user code. The user assigns to it, so the member variable of the class gets the new value.

You seem to be worried about keeping encapsulation here. From this point of view, in the form you wrote, your getter is incorrect. In most cases, we return a value or a permalink:

int get() { return x; }

const int& get() { return x; }


This way, the user will not be able to mutate the returned member variable. Getter is a dumb function to "get me back", so in most cases, we will assume that it should not mutate the internal state of the class. To be careful, we often become permanent members of getters as well:

const int& get() const { return x; }


There are of course exceptions (in particular lazy eveluation ). And also the user can expel the constant. But that's another story.

See also: Const-correctness , Mutator_method , The Definitive Guide and List of C ++ Books (Best Practices and Intermediates)



All Articles