Accessor functions in class c++

7.2k Views Asked by At

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?

4

There are 4 best solutions below

0
On

The data member 'a' is not of type 'const int'

As far as the const member function getA is concerned, yes it is.
All non-mutable members are consted from the point of view of a const member function. Therefore, you are trying to bind a const int to an int&.

Also when I change the return type to int it works. why?

You can copy a const int into an int just fine.

1
On

Let's look into this code:

const int *ptr = ...;
int &ref = *ptr; // case 1
int var  = *ptr; // case 2

Will case 1 compile? No, because ptr is a pointer to constant int and assigning that to non const reference breaks that contract. Will "case 2" compile? Yes, because you "make a copy" ie only reading value from a constant.

Now in your case, method you write is equivalent to this:

int& getA() const { return this->a; }

You do not have to use this explicitly, but it is there anyway. Saying const after method basically makes this type const A * inside that method. Now if you try to assign (return is similar to assign) this->a to int &, you get "case 1", if you try to assign to int you get "case 2" as above.

2
On

Because you specify that getA() is const. Returning a non const reference to a member variable from a method declared as const would allow to modify the value referenced.

If you want a read-only accessor then just declare the accessor as

const int& A::getA() const

otherwise you must remove constness from the method.

Turning the returned value to an int is allowed because you are not returning a reference anymore, but a copy of a so there is no way to modify the original member variable.

Mind that you are allowed to have them both available:

int& getA() { return a; }
const int& getA() const { return a; }
0
On

The error comes from the fact that the member function is marked const. You cannot return a non-const reference in a const method because the calling location can modify the value:

a.getA() = 2;

When you return an int it copies that value and makes the above produce a compilation error.