Constructors vs Assignment c++

154 Views Asked by At

I am having a huge disconnect while trying to figure out constructors. My question is this: Are constructors with initialization lists replacing the set methods of a class? For example:

Class Rock
{
private: 
    double Weight;
public:
    void setWeight(double)
    { Weight = wei; }
    double getWeight()
    { return Weight; }
    double calcWeight()
    { return Weight *= 2; } 
}

Would using a constructor with initialization list that looks something like: Rock::Rock(double): Weight(w) {} replace using the set method?

2

There are 2 best solutions below

2
On

Setters and constructors serve completely different purposes, and one never "replaces" the other.

Constructors set up the initial state of instances, and setters allow you to change that state after construction.

That being said, if you find yourself doing something like the following:

Rock rock;
rock.setWeight(3);

Then what you are actually doing is setting the initial state of the rock. In that case, then yes, a constructor taking the weight as a parameter is preferable.

However, notice that this is a distinction that happens at the point where the class is used, not when it is declared.

2
On

Constructors and so called setter methods are two distinct things and are used in different contexts. Unlike setters, constructors may be used implicitly (e.g. a default constructor is used when we have a standard library container with elements of the class type), when an object is being instantiated.

std::vector<Rock> vec_of_rocks; // Will contain default initialized Rock objects

Moreover, constructors allow us to control how an object will be instantiated when we copy-construct it (as in Rock b(a);), and in few other scenarios.

Meanwhile, a user of the class can use setter methods to modify existing objects explicitly. Most often setter method is used to provide safe and controlled way to modify some private data member.

// First check for the weight to be non-negative, then set it
void Rock::setWeight(const double &d)
    { if (d >= 0) Weight = d; else Weight = 0; } 

Rock r_object; // Default initialized object r_object (by default constructor) 
r_object.setWeight(3.14); // In the user-code, we modify default initialized value

Note, we can intorduce constructors which initialize objects with specified values, via constructor member initializer lists.

Rock::Rock(const double &d) : Weight(d) {} // Constructor that takes an argument, not a default one
Rock r_object_2(1,12); // Uses the defined above constructor, not a default one