Reasons for defining non-const 'get' member functions?

  • A+
Category:Languages

I'm working on learning C++ with Stroustrup's (Programming Principles & Practice Using C++) book. In an exercise we define a simple struct:

template<typename T> struct S {   explicit S(T v):val{v} { };    T& get();   const T& get() const;    void set(T v);   void read_val(T& v);    T& operator=(const T& t); // deep copy assignment  private:   T val; }; 

We're then asked to define a const and a non-const member function to get val.

I was wondering: Is there any case where it makes sense to have non-const get function that returns val?

It seems much cleaner to me that we can't change the value in such situations indirectly. What might be use cases where you need a const and a non-const get function to return a member variable?

 


get() is callable by non const objects which are allowed to mutate, you can do:

int l = 0; S<int> r(l); r.get() = 1; 

but if you make r const as const S<int> r(l), the line r.get() = 1 no longer compile, not even to retrieve the value, that's why you need a const version const T& get() const to at least to able to retrieve the value for const objects, doing so allows you do:

const S<int> r(l) int val = r.get() 

The const version of member functions try to be consistent with the constness property of the object the call is made on, i.e if the object is immutable by being const and the member function returns a reference, it may reflect the constness of the caller by returning a const reference, thus preserving the immutability property of the object.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: