0

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"

2
  • G++ gives a better message whining about missing const: error: passing 'const value_type' {aka 'const Obj'} as 'this' argument discards qualifiers Commented Mar 25, 2022 at 21:11
  • inline int getVal() { return val; } should be int getVal() const { return val; } by the way. Commented Mar 26, 2022 at 0:04

2 Answers 2

1

You need to declare getVal() as const:

inline int getVal() const { return val; }

instead of:

inline int getVal() { return val; }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.