I have a problem with whether making class members constant or not. Let me give an example.
#include <iostream>
class ValueClass
{
int ival;
public:
void set(int i) {ival = i;}
int get() {return ival;}
};
class XXX;
class ABC
{
ValueClass vc;
public:
int getval() const {return vc.get() ;}
friend class XXX;
};
class XXX
{
std::vector<ABC> abclist;
void Invalidate()
{
// Iterates through abclist and modifies ValueClass members.
// e.g. abclist[i].vc.set(i);
}
};
class QWE
{
const ABC & abc;
public:
QWE(const ABC & abc_): abc(abc_) { }
const ABC & getABC() { return abc; }
};
int main()
{
ABC abc;
QWE qwe(abc);
std::cout << qwe.getABC().getval() << "\n"; // Compiler error
}
My ABC class holds an instance of ValueClass which is responsible for having getter and setter for an int value. Also QWE class has an ABC member and I need to obtain this member. I am told that returning the abc as non-const is a very bad practice. But here comes the problem, I can not use non-const vc in a const int getval() function and I simply can not make it const because in another thread XXX::Invalidate() is called. This function changes the data in ValueClass with respect to some incoming data.
Obviously there is something wrong with my design, I can not blame the C++ language. How can I solve this problem?
Make get() const in ValueClass
Probably should do the same for getABC
This means that this method does not change the object it is called on.