No up-casting During Array Initialization

Interesting. Today our QA guy came to me and told me that SunOS, and HP machines were not compiling due to a section of my code. I took a look and low and behold it is my code (variables names changed)

ParentBar* (*PtrFunc[])( ) =
{
      ChildABar::instance,
      ChildBBar::instance,
      ChildCBar::instance
};

The problem was that ChildABar::instance is a Singleton which returns only ChildABar*. Now it is perfectly fine to upcast it so that ChildABar* passes to ParentBar* which is the pointer to parent class of ChildABar, ChildBBar and ChildCBar. But for this case it is not because the array is in declaration/initialization phase and not assignment phase.

It's fine to assign child/derived class pointer to parent/base class pointer ( called upcasting ), but it cannot be done during initialization. So to fix this problem, I just when into ChildABar, ChildBBar and ChildCBar classes and created another static member function call getParentBar() that returns the pointer to parent class ParentBar* ,

ParentBar* ChildABar::getParentBar( )
{
      return _instance;
}

where _instance is of type "static ChildABar*".

So I get

ParentBar* (*PtrFunc[])( ) =
{
      ChildABar::getParentBar,
      ChildBBar::getParentBar,
      ChildCBar::getParentBar
};

This then fixed the Sun and Hp compiler problems which are much more picky and strict than Linux, which only gave me warnings during compilation. This is just something I learned today.

No comments: