Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should constructors accept parameters or should I create setters?

Tags:

c++

oop

class

I have two options. Either make a class that accepts a lot arguments in its constructors, or create a lot of setter methods and an init method. I'm not sure which is preferred option, should some arguments be accepted in constructors, while others could be manually set via setter? Or am I over-thinking this?

This is a relevant question, also by me: Conflicts between member names and constructor argument names.

like image 849
corazza Avatar asked Oct 10 '12 15:10

corazza


People also ask

Should I use setters in constructors?

You should not call getters and setters from the constructor. A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will. The only way to guarantee initialising the fields is to assign them.

Do constructors need to have parameters?

Default Constructor – A constructor that accepts no parameter is called Default Constructor. It is not necessary to have a constructor block in your class definition. If you don't explicitly write a constructor, the compiler automatically inserts one for you.

Do constructors accept parameters?

Constructors can also take parameters, which is used to initialize attributes.

What is the difference between setters and constructors?

The constructors are used to initialize the instance variable of a class or, create objects. The setter/getter methods are used to assign/change and retrieve values of the instance variables of a class.


1 Answers

If after you create an object you have to call set or init to actually use it... well, that's just an awful design.

If the object is usable without some of the members initialized the way you want them to be, you can set them later on.

The golden rule here is - if you create an object, you should be able to use it without doing any other sort of initialization.

Expanding on the answer:

Say you have a shape with 10 sides, 10 corners, a color and a name, that can be connected to a different shape. The constructor should look like:

 MyShape(Point c1, Point c2,...., Point c10, Color c, Name n)

As you can see, I've omitted the connected shape because it can sensibly be set to NULL if the current object is not connected. However, in the absence of any of the other parameters, the object isn't valid, so they should be set in the constructor.

A possible overload (alternitively a default argument) can be:

 MyShape(Point c1, Point c2,...., Point c10, Color c, Name n, 
                                      MyShape* connectedShape /*=NULL*/)
like image 94
Luchian Grigore Avatar answered Sep 21 '22 22:09

Luchian Grigore