rsjethani
rsjethani

Reputation: 2227

how to properly initialize a class containing many data members?

Suppose a class contains around 10 data members then what would be the proper way to initialize an object of that particular class? Create a constructor with 10 parameters or just provide a default constructor then use setter member functions or something else? Basically I want to know how it is done in actual real life code? thanks.

Upvotes: 0

Views: 226

Answers (3)

Rick Falck
Rick Falck

Reputation: 1778

Isn't this really an OOP and design question?

What is the object here? Are all 10 fields attributes of that object? Can some be further grouped under another class?

Do you always have all 10 pieces of data when you need to instantiate the class? You can make constructors for the pieces you have and/or do setters/getters.

Upvotes: 0

TheSOFan
TheSOFan

Reputation: 67

Another [design] problem is that if you use class with that many arguments as a base class and then add more arguments (due to a requirement, for example), you may well forget to initialize them. So, yeah, refactor.

Upvotes: 0

John Dibling
John Dibling

Reputation: 101456

In actual real life code, I would be very reticent to have a class with 10 parameters that need to be set.

But also in real life, I know that this happens much more often than I would like. So here is what I would do:

First, evaluate your design. Do you really need all that stuff?

Second, if you really do need all that stuff, or if there's no way out due to a legacy design, then I would require every parameter in the constructor, and make the default constructor private. Everything should be initialized in an initialization list.

Sometimes when the data members and the class methods are sufficiently decoupled I would prefer to move all the data members to their own struct, and then have a member of that struct in the class. Take that struct by const reference and assign it in the init list. Make the struct member const.

Upvotes: 2

Related Questions