I’m getting stuck with MFC C++ polymorphism, here’s my problem:
I have a class, let’s say A, that implements a lot of useful stuff, but every object I need to instantiate from it, requires a little customization, so I decided to derive each of my classes (i.g.: A1, A2… ).
Now, the initialization of these objects require some operations that are the same for ALL subclasses, so I’ve build a static method that does this task and here comes the problem:
void CFastInit::FastGrid( const CStatic &stPosition, A *pGrid, UINT nID, CWnd *pWnd )
{
stPosition.GetClientRect( rctGriPos );
stPosition.MapWindowPoints( pWnd, rctGriPos );
pGrid->Create( WS_CHILD | WS_VISIBLE, rctGriPos, pWnd, nID );
pGrid->SetWholeRowSel();
}
From the Debugger I can see that pGrid is of right type ( A1, A2… ), but the call:
pGrid->Create(
is done to A::Create and not to A1::Create or A2::Create. Is there a workaround to this?
Seems you have a static function
FastGrid(). Note that this function is shared by all objects of the base class, and all objects of any class derived from base.In this function, you are getting a pointer to the base class as a parameter:
A *pGrid, and then make a function call on that pointer:pGrid->Create().Now, if
pGridpoints on a derived class object, you need theCreate()function to bevirtual, if you want to have polymorphism. If it is not virtual, theCreate()function of a base class will always get called.Probably you want something like this:
Output:
If you remove the
virtualkeyword, the output will beand that’s what you have now. Also note that the static function in my example could be also called like this:
derived::foo( new derived() );, that would not change anything.