Luigi Istratescu
Luigi Istratescu

Reputation: 97

Why should I use constructors if I can use get and set?

OOP is giving me a bad headache :( because I understand how constructors work but I don't understand what are they there for.

I have a class called Player that looks like this:

class Player
{
private:
    std::string name;
    int health;
    int xp;
public:
    //Overloaded Constructor
    Player(std::string n, int h, int x) 
        {
        name = n;
        health = h;
        xp = x;
        }       
};

int main()
{
    Player slayer("Jimmy", 1000, 200);
    return 0;
}

Insted of using the constructor there (I have no idea what it does or what is it for) I could use set_name and get_name methods where I would set the name - and do the same with health and xp - and then get the name using functions. So, a constructor replaces functions???

What's the purpose of it if it doesn't replace set & get then? Also, the same constructor above I can use it to initialize my attributes and avoid garbage:

Player(std::string n, int h, int x) : name{n}, health{h}, xp{x} {}

But then I can also do this:

Player(std::string n, int h, int x) : name{n}, health{h}, xp{x} { name = n; health = h; xp = x;}

I don't understand, what does all that mean? I know in the first case I am initializing it, and in the second I am saying that the name health and xp equals whatever I am going to set it to.

Knowing all this information, I still don't know what is a constructor and what should I use it for. It's very confusing.

Upvotes: 0

Views: 1031

Answers (1)

Tumbleweed53
Tumbleweed53

Reputation: 1551

A constructor serves a very important purpose in C++. With a properly written constructor, you know that an object is always valid. It can never be allocated but somehow in an invalid state.

Typically, if your class has a set method which sets all of its state, you would simply have the constructor execute set with a proper set of default values. Then you don't need to duplicate code, and your object has the nice property of being in a valid state from the beginning.

Upvotes: 1

Related Questions