Author Topic: Late initialization problem  (Read 17274 times)

Krice

  • (Banned)
  • Rogueliker
  • ***
  • Posts: 2316
  • Karma: +0/-2
    • View Profile
    • Email
Late initialization problem
« on: March 09, 2010, 05:22:40 PM »
I have Object base class and let's say derived Actor class. Now, Object has a virtual get for some information which of course works when the object is constructed. The problem is that when you try to get that information in Actor's constructor, it fails, because the Actor part isn't constructed yet! This small problem has troubled me for some while. What people do in this situation? Maybe remove virtual function and use generic routine in base class for different object types?

scaught

  • Newcomer
  • Posts: 18
  • Karma: +0/-0
    • View Profile
Re: Late initialization problem
« Reply #1 on: March 09, 2010, 11:28:45 PM »
Usually, I have an Init() function that I do post construction.  The main benefit is I can have the initialization fail gracefully without resorting to throwing exceptions. It's also useful for resetting objects back to their initial state without reconstructing it.  The downside is you have to make an explicit function call for it post-construction.

If you start making generic functions in your base class, you'll end up with a mess of interdependent code.

Krice

  • (Banned)
  • Rogueliker
  • ***
  • Posts: 2316
  • Karma: +0/-2
    • View Profile
    • Email
Re: Late initialization problem
« Reply #2 on: March 10, 2010, 09:08:47 AM »
I'm using intialization list for Actor which is constructed in middle of final object like Creature: Object - Actor - Creature so it's difficult to avoid calling the constructor and besides the needed information for Actor must be set in Actor's constructor, because Creature is then using that in its own constructor. The problem itself isn't that difficult, because I can always provide the needed information in Actor's constructor from the type of object and the data related to that object type, which is totally independent from Object class structure itself. I'm just wondering if there is something in the design I have somehow missed and could learn some new way to do this.

Xecutor

  • 7DRL Reviewer
  • Rogueliker
  • *
  • Posts: 263
  • Karma: +0/-0
    • View Profile
Re: Late initialization problem
« Reply #3 on: March 10, 2010, 03:00:25 PM »
I'm using virtual Init(). Works fine for me.
Child class is calling Init of base class in own Init.
It's not too error-proof. But current version of C++ is mostly lacking
this kind of things anyway.

You can't call virtual methods for initializers.
But you can call them from body of constructor.
Just move initialization of fields that are dependant on
virtual getters to body of constructor.