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:
- 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 referencegetx()
,gety()
accessors not work more. - you need const , nonconst version, have 2 methods against 2 methods - there no savings in writing reference version.
- you cannot apply boundary checks, e.g.
phi
has between0
,2*pi
polar coordinates. cannot save against e.g.p.phi() = 2500.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
Post a Comment