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?
Because you specify that
getA()isconst. Returning a nonconstreference to a member variable from a method declared asconstwould allow to modify the value referenced.If you want a read-only accessor then just declare the accessor as
otherwise you must remove constness from the method.
Turning the returned value to an
intis allowed because you are not returning a reference anymore, but a copy ofaso there is no way to modify the original member variable.Mind that you are allowed to have them both available: