c++ - Reference return for setter -


a. how useful/cumbersome following trick of using same function getter setter, returning reference?

b. how practice of adding const end of function declarations in case of getters , setters?

#include <iostream>  class {   int varreadwrite_;   int varreadonly_;   int varrestricted_;  public:   a() : varreadonly_(25) {}   virtual ~a() {}    int& varreadwrite() { return varreadwrite_; }   int varreadonly() { return varreadonly_; }   int varrestricted() { return varrestricted_; }   void setvarrestricted(int i); //throwable  };  int main(int argc, char *argv[]) {   a;   a.varreadwrite() = 45;   std::cout << a.varreadonly() << a.varreadwrite() << std::endl;   return 0; } 

the reasons, why chose design was:

  1. ease of access of explicitly read-only or explicitly writable variables.
  2. the restricted (i dont know else call them), variables, require sanitization , filtering before being assigned -- these variables might require explicit setter.

using boost fusion map interesting possibility shown here

update

const reference members interesting read-only access variables, e.g.

class {   int ma; public:   int& a;   a(int a_ = 0) : ma(a_), a(ma) {} }; 

practically comes effort code copy , move constructors, acceptable compromise for me.

cpp reference copy construtor says

the implicitly-declared or defaulted copy constructor class t defined deleted if... t has non-static data members cannot copied (have deleted, inaccessible, or ambiguous copy constructors);

a. how useful/cumbersome following trick of using same function getter setter, returning reference?

returning reference internal members in general is not recommended since way give easy access others change object internal state without using method provided object's class api. thus, difficult track kind of changes in code. in general changes in internal state of object should possible through methods belongs class api.

b. how practice of adding const end of function declarations in case of getters , setters?

if refer adding const methods like:

void printstate() const 

then in general doesn't make sense setters. const in case means this method doesn't change object state. it's commitment give caller say: i not change object state call. in general it's practice since helps during design think methods , see 1 modifying object state or not. additionally, it's defensive programming since it's recursive: if pass object method reference (through pointer or reference) can't call const methods unless method marked const also. prevents changing object state error.


Comments