I'm trying to use const keyword correctly in my code. I have a class A that have some other classes B in and std::array as member variable.
I have an accessor to get one of A's B member.
class B { public: int getMember() const; }; class A { public: B& getB(const size_t idx) { return m_bCollection[idx]; } private: std::array<B, 10> m_bCollection; }; Then I added a function to serialize an instance of A for yaml-cpp
YAML::Emitter& operator<<(YAML::Emitter& out, const A& a) { // some stuff here, and then: out << a.getB(1).getMember(); return out; } This does not compile since the call to getB violates the const modifier for a argument of my serializing function.
error: passing ‘const A’ as ‘this’ argument discards qualifiers
I could overload my getB method to have a constant version of it, but this does not seems very clean...
B& A::getB(const size_t idx); const B& A::getB(const size_t idx) const; I have this issue on other similar classes as well and have const-overloaded a lot more method. This modification seems a mess to me. I think I missed a cleaner way to achieve my goal (having a const A& as serializer argument).
I only use const members of the non-const B instance reference returned by the const A instance. What should I refactor here to have clean code that follow c++ good practices ?
const B& A::getB(const size_t idx) const;is the right way, the more you can put your membersconstthe better it is. Note you can also have aconstand a nonconstversion of your membersconstand notconstoverload is clean C++.