I override the base-class function ShowProperties in a sub-class, but still the base-class function gets called. Why is this?
class hierarchy:
class CDiagramEntity : public CObject
{
public:
virtual void ShowProperties( CWnd* parent, BOOL show = TRUE );
}
class CNetworkSymbol : public CDiagramEntity
{
/*NO 'ShowProperties' Function*/
}
class CDeviceEntity : public CNetworkSymbol
{
/*NO 'ShowProperties' Function*/
}
class CSwitch : public CDeviceEntity
{
public:
virtual void ShowProperties( CWnd* parent, BOOL show = TRUE );
}
Use:
/*Use Here*/
{
CDiagramEntity* obj = GetSelectedObject();
if( obj )
{
CSwitch* sw = (CSwitch*)obj;
sw->ShowProperties( this );
/*calls CDiagramEntity's function, not CSwitch's function*/
}
}
PS:
- As @iammilind suggests, I removed virtual from CDiagramEntity and use casting, the function of CSwitch is called, and from the properties it shows(the properties can only be changed to what it shows when CSwitch is created), I am quite sure it is a CSwitch.
-
As @user1610015 comments, if I use
CSwitch* sw = dynamic_cast<CSwitch*>(obj);it returns
NULL. -
As @Andrian Sham says, I got the problem’s reason:
GetSelectedObject()--->finally calls---> { CDiagramEntity* result = NULL; if ( index < m_objs.GetSize() && index >= 0 ) result = static_cast< CDiagramEntity* >( m_objs.GetAt( index ) ); /*m_objs is defined as: CObArray m_objs;*/ return result; }
m_objs:
CObArray m_objs;
And the object is stored as:
...( CDiagramEntity* obj )
{
obj->SetParent( this );
m_objs.Add( obj );
SetModified( TRUE );
}
But can someone explain this in more details?
I am not sure how you do your debug. You said you can see a member var of CSwitch. If you mean you inspect
CSwitch* sw = (CSwitch*)obj;and see such var insw, you are in fact getting in wrong. Debugger is simply “interpreting” the piece of memory pointed byswas it is a CSwitch. It doesn’t mean that it is really a CSwitch.I can only thought of a case. Have you put the object instance in any STL container and get it out to put it as the select item?
(I forgot MFC totally, this is just an example)
You may think you entities[i] should return an instance of CSwitch but it is not.
(This is the best I can guess if you are pretty sure that the selected item should be a CSwitch)