Constructor vs Functions

I have an odd question :
class Square{
double side_A;
double side_B;
double result;
Square():side_A(0),side_B(0){result=(pow(side_A,2));}; // constructor
Square(double x, double y){side_A=x;side_B=y;result=(x*y);};//Constructor
Would it be standard practice to put the computation right in the constructor?
That way, I wouldn't need the function unless i did not want it automatically
computed on creation of the obj. Am I right?
I'm not sure if this is something I should even be doing or just stick to using functions for that kind of stuff and just let constructors initialize the class variables.

Thank You in Advance
Looks like what you're calculating is a property of the class; namely, the area of the square.

In which case, nothing wrong with having a member variable area and calculating it upon construction.

Why do you have two values for the sides of the square? It's a square. They will be the same. You just need one value for the side.
Because the one with no args will be for the square, the one with two args is for rectangle. It just didn't seem like I should create a whole separate class for something I could do by overloading. That is the only reason I did it that way.
Last edited on
I would suggest that if you intend this class to represent things that are not a Square, naming the class Square is not a good idea.
Because the one with no args will be for the square

What kind of square has side length 0 and area 0?

Rectangle( double x ) // square rectangle
: side_A(x), side_B(x), result(x*x)

Rectangle( double x, double y )
: side_A(x), side_B(y), result(x*y)

An object should always be in coherent, predictable state.
For example, your in class there is probably invariant: side_A * side_B == result
Every method that would change side_A or side_B must update the result too.

Since the result is a member, the constructors must set it right, preferably by initialization.
If the constructor does not compute the result, and something can read the result before a function is called to update the result, then the reader receives garbage.
Topic archived. No new replies allowed.