Nicholas Nicholas - 1 month ago 15
C++ Question

Return function type example in C++

Current

get()
member function in class
MyClass
is defined as below, the return type is
const int&
. My question is what would be the difference if I defined
get()
function as


int& get() const



or


int get() const



? And which way is recommended?

#include <iostream>
using namespace std;

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

void print (const MyClass& arg) {
cout << arg.get() << '\n';
}

int main() {
MyClass foo (10);
print(foo);

return 0;
}

Answer

There's really nothing wrong with this code; logically it accomplishes more or less the same thing after the compiler inlines the get() method.

There's quite a big difference in some degenerate callers though:

const int *iptr = &foo.get(); // returns the address of x in the class.

On the other hand had you declared as follows:

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

const int *iptr = &foo.get(); // Error!

I don't see any good reason for int& here. If you don't have one, people will frown on this code. Normally if people are expected to keep pointers to things around you don't return them by reference. The only reason you would want to return a pointer to a member is so that somebody can auto-pickup changes to it; and I have never seen a good use for that though I can imagine why some such thing might exist.

As for selbie's comment about assigning to it; it's a const reference; assigning to it is a compile time error.

Comments