object - C++ when is the right time to use a no default constructor vs. getters and setters vs just invoking the variables in the class directly -
ie. when have class say
class color() { private: std:: string _colors public: color(); color(std::string colors); std::string setcolors(std::string colors); std::string colors; ~color(); }
and wanted call in class main assign variable colors.
#include "color.h" using namespace std; int main() { color c; c.colors = "blue"; //is correct color("blue"); //is correct c.setcolors("blue");//or correct. return 0; }
when correct time use either?
the answer is: depends.
on you, preferences, coding guidelines of team, how oo code is, syntactic sugar language offers, etc. becomes question of usable/readable code.
my (arguably general) advice is: whenever writing simple code , class resembles data more objects, totally ok give public access members (you might want use structs in c++ though instead of class, make decision more obvious). not easier write in first place, easier use read endless get-set combinations.
on other end of spectrum getters , setters allow control access internal members, e.g. validation, or update internal state accordingly. afaik encapsulation , keeps more complicated oo-code sane.
just avoid having both methods same members, becomes confusing , irritating.
Comments
Post a Comment