Should I use virtual 'Initialize()' functions to initialize an object of my class?

后端 未结 13 1431
孤独总比滥情好
孤独总比滥情好 2020-12-17 14:33

I\'m currently having a discussion with my teacher about class design and we came to the point of Initialize() functions, which he heavily promotes. Example:

13条回答
  •  醉梦人生
    2020-12-17 15:14

    One argument for preferring initialization in the constructor: it makes it easier to ensure that every object has a valid state. Using two-phase initialization, there's a window where the object is ill-formed.

    One argument against using the constructor is that the only way of signalling a problem is through throwing an exception; there's no ability to return anything from a constructor.

    Another plus for a separate initialization function is that it makes it easier to support multiple constructors with different parameter lists.

    As with everything this is really a design decision that should be made with the specific requirements of the problem at hand, rather than making a blanket generalization.

提交回复
热议问题