For example I have an accessor function for a class:
class A {
public:
int a;
int& getA() const;
};
int& A::getA () const {
return a; // error: invalid initialization of reference of type 'int&' from expression of type 'const // int'
}
The questions are:
1. The data member 'a' is not of type 'const int', so why the error?
2. Also when I change the return type to int it works. why?
As far as the
const
member functiongetA
is concerned, yes it is.All non-
mutable
members areconst
ed from the point of view of aconst
member function. Therefore, you are trying to bind aconst int
to anint&
.You can copy a
const int
into anint
just fine.