Home > Software engineering >  Calling functions inside of const references
Calling functions inside of const references

Time:03-26

Hi I am trying to have a getter in my class that returns a "read-only" reference to a vector of objects. Each of those objects its own variables and functions, that I need to call. The way that I am trying to set this up is to have the getter in the main class return a const reference. However, I don't seem to be able to access the values of the objects held in the vector. Is there a better way to do this? Here is a smallest reproducible example. Thank you.

#include <vector>
class Obj
{
private:
    int val;
public:
    Obj() { val = 10; }
    inline int getVal() { return val; }
};

class Foo
{
private:
    std::vector<Obj> obsVec;
public:
    Foo()
    {
        Obj a;
        Obj b;
        obsVec.push_back(a);
        obsVec.push_back(b);
    }
    const std::vector<Obj>& getConstRef() const { return obsVec; }
};

int main()
{
    Foo foo;
    foo.getConstRef()[0].getVal(); // Here is where I get the error
    return 0;
}

The error that I get is:

Error (active) E1086 the object has type qualifiers that are not compatible with the member function "Obj::getVal"

CodePudding user response:

You need to declare getVal() as const:

inline int getVal() const { return val; }

instead of:

inline int getVal() { return val; }

CodePudding user response:

foo.getConstRef()[0] returns const A &, but getVal is not marked const.

Also note that inline is useless here, since functions defined (rather than declared) in class body are implicitly inline.

  • Related