how to best instanciate a new class

Started by
12 comments, last by doynax 18 years, 5 months ago
hello, say i want to create a new instance of a class which has quite a lot of members. is it better to provide them all as parameters to the constructor or to assign them all as public variables. example1:

//constructor
I::I(type var1, type var2, type var3, type var4, ...)
{
x1 = var1;
x2 = var2;
x3 = var3;
x4 = var4;
}


var * I = new I(var1, var2, var3, var4, ...);


; example2:

var * I = new I();

I->x1 = var1;
I->x2 = var2;
I->x3 = var3;
I->x4 = var4;
...


the problem is, i really have a lot of variables and the constructor looks kinda weird with all these parameters.
Advertisement
I'd limit the constructor args to only necessary items, initialize all the others in the constructor initializer lists to sensible values, and allow the caller to modify them through modifier functions, rather than making them public. Using modifier functions you can validate the input for correctness before setting it and assert or whatever. Public variables if the class is a POD type.
thank you
well, they are all necessary.

what is a POD?
Plain-Old-Data.
Unless it is one of those odd homeworks, just use important arguments for constructors, for example the size of an array the class would use, or if the class seriously requires the path of a file that's a good one too. For the rest use default, dummy values
------ XYE - A new edition of the classic Kye
It Depends.

On the number of parameters, whether there are sensible values for them, whether they have any logical groupings, whether some can be calculated from others (some may be explicitly intended as caches of precalculated values; others may turn out to be unnecessary upon further reflection), etc.

You may consider the Named (Constructor) Parameter Idiom.
Although its kind of an immature guide, when the parameter list extends past the 80th column, there are probably too many. Same goes for functions and the like. What you should probably confine to the constructor is just the data that makes an object relatively unique. For example, a class containing data about a ball, you'd need it's radius, color, location on the screen. But for this same ball, you probably wouldn't include metadata like which direction its rolling, or how much of a bounce it has to it.
william bubel
I recently started trying to do the stuff Zahlman links too, and it works really well for most lengthy constructors that often have default parameters.
Very interesting link Zahlman, thanks.
Quote:Original post by Zahlman
You may consider the Named (Constructor) Parameter Idiom.

Or, preferably if you have Boost, Boost.Parameter, since it won't affect the design of the rest of the class.

This topic is closed to new replies.

Advertisement