c++ - Get and Set Function vs Referenced Functions -


i have code:

#include<iostream> #include<string>  class test { public:     std::string& gettext()     {         return text;     }      void display() { std::cout << text << std::endl; }  private:      std::string text; };  int main() {     test test;      test.gettext() = "testing";     test.display(); } 

now referenced function works , setter under 1 function name. wanted know beneficial use method or more beneficial use separate , set method. or make more sense make variable public.

there no difference (or @ least not much) in terms of performance, behavior etc. between 2 versions. there other things keep in mind reference version:

  1. you can return reference actual member of object. if there no such member, lost. also, providing reference means giving hint on implementation, leaking abstraction class should provide. makes changing implementation hard. consider class point, implemented x , y coordinates. won't able provide referenced access polar representation of point, nor able change implementation polar coordinates, because after reference getx() , gety() accessors not work more.
  2. you need const , nonconst version, have 2 methods against 2 methods - there no savings in writing reference version.
  3. you cannot apply boundary checks, e.g. phi has between 0 , 2*pi polar coordinates. cannot save against e.g. p.phi() = 2500.4;
  4. you have getter. there cases setter needed. it's not possible have setters reference version. , using trivial setter method setter-only members, reference access other members inconsistent , confusing reading code.

so while there cases, referenced access useful, should use classic getter , setter methods of time.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -