How to set base class members before derived class constructor is called?

安稳与你 提交于 2019-12-04 22:00:19

You don't really have a choice. Either the derived class knows about the initialisation needs of the base class (because the base class needs that information in its constructor/initialisation function), or you have to move the derive-class' initialisation out of its constructor (to be called by the client after it initialised the base class).

If the list of members that need to be set on the base class is long, you could package them all in a structure and pass that, via the derived class, to the base class.

The base-class constructor is called before the derived class constructor, so set the values in your base-class constructor.

I'm not quite sure what you're tryign to accomplish here but I can make a few observations. It looks like you may be trying to implement two-phase construction.

First, if you want to use the base class constructor you will have to pass through the values from the derived constructor. There's no other mechanism in the language to do it, so if that's not an option (or at least not one you want to entertain) then you'll have to use an additional external interface.

To answer your final question, the members of the base are always initialized before the derived constructor is called. I'll assume you want to make sure they're set before using Update for example.

What about making Init protected, and renaming Set to something like SetAndInit and forcing it to always do the set before it calls the Init function. That prevents you from calling Init before the base members are set and still gives you a relatively similar interface.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!