about constructors

Hello all , and thank you for answering my question in advance

My question :
if i create a constructors , can i say that i should not use setters ?
since i am going to do the same thin which is initilizing the member variables ?
Thanks again
Yes constructor is used as a setter to initialize the member variables. But you can have the user defined setter and getter as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Time
{
    public:

        string getTime()
        {
            stringstream convert;

            convert << hour << ":" << minute << ":" << second;
            return convert.str();
        }

        void setTime(const std::string &time)
        {
            char throwAway;
            istringstream convert(time);

            convert >> hour >> throwAway >> minute >> throwAway >> second;
        }

    private:
        int hour;
        int minute;
        int second;
};
> 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_ ;
};
Topic archived. No new replies allowed.