> if i create a constructors , can i say that i should not use setters ?
No.
A constructor is used to
initialise the state of an object.
For many objects, the observable state of an object can change after it is initialised; while for some others, it can't. (To support this notion, we have the
const qualifier: the observable state of a
const book can't change once it has been initialised.)
A setter (mutator, modifier) is a member function which allows the user of an object to initiate a (possible) change in the observable state of the object. A getter (observer, inspector, selector) is a member function which allows the user of an object to access its observable state. (The
const specifier is used to support this notion; getters are "const member functions".
http://www.parashift.com/c++-faq-lite/const-member-fns.html)
If the object in question is (an obedient) dog, "Sit!" is a setter (no pun intended). In oo jargon, it is a message sent to the dog object which causes it to change its state.
(In contrast, "Stay!" is a message sent to the dog object which inhibits it from any sua sponte change of state.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
struct person
{
person( std::string name, std::string address, int post_code ) // constructor; initialise state
: name_(name), address_(address), post_code_(post_code) { /* validate, throw on error */ }
void move_to( std::string new_address, int new_post_code ) // not const: setter (aka mutator); modify observable state
{ /* validate ... */ address_ = new_address ; post_code_ = new_post_code ; }
std::string address() const // const: getter (aka inspector); access observable state
{ return address_ + "\nPost Code: " + std::to_string(post_code_) ; }
private:
std::string name_ ;
std::string address_ ;
int post_code_ ;
};
| |