Differents member functions and how to implement them in C++

Good day admin

I need better explanations on how to implements the below c++ member functions.


1
2
3
4
5
6
7
8
9
10
11

    int get() {return x;}

    int& get() {return x;}

    int& get() const {return x;}

    const int& get() {return x;}

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



Some of the code above return error message some of it does not.

Thanks.
Last edited on
First of all, you can "overload" functions, i.e. you can have multiple member functions of the same name.

But only as long as they are distinguishable by their parameters. Otherwise, as in your code, you'll get error:

overloaded function differs only by return type


Furthermore, you can not return a non-const reference to a member variable from a const member function!

int& get() const { return x; }

(Within a const member function all member variables, except for mutable, effectively become const)

This results in:
1
2
error C2440: 'return': cannot convert from 'const int' to 'int &'
Conversion loses qualifiers



Finally, not declaring the following member function as const, even though it returns a const reference, doesn't make a whole lot of sense to me. There's not really a reason why it shouldn't be a const function:

const int& get() {return x;}

That's why your last functions makes more sense to me:

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


To make a long story short:
1
2
3
4
5
int        get1()       { return x; } // <-- return a "copy" of 'x' by value (okay)
int&       get2()       { return x; } // <-- return a mutable reference to 'x' (okay)
int&       get3() const { return x; } // <-- return a mutable reference to 'x' from const function (error !!!)
const int& get4()       { return x; } // <-- return a const reference to 'x' from a non-const function (possible though weird)
const int& get5() const { return x; } // <-- return a const reference to 'x' from a const function (okay) 
Last edited on
Ok. Thanks.
If a member function doesn't change a member variable and doesn't return a ref, then the function should be marked as const. Also if the function won't throw an exception then it should also be marked as noexcept.

So:

1
2
3
4
5
6
7
8
class MyClass {
public:
	int get() const noexcept { return x; }
	int& get() noexcept { return x; }

private:
	int x{};
};

Topic archived. No new replies allowed.