A static check tool shows a violation on the below code:
class CSplitFrame : public CFrameWnd
...
class CVsApp : public CWinApp
CWnd* CVsApp::GetSheetView(LPCSTR WindowText)
{
CWnd* pWnd = reinterpret_cast<CSplitFrame*>(m_pMainWnd)->m_OutputBar.GetChildWnd(WindowText);
return pWnd;
}
Error Message: Class 'CSplitFrame' inherits from class 'CWnd'
Description: Avoid casts down the inheritance hierarchy. This rule detects casts from a base class pointer to a subclass pointer.
Benefits: Allowing casts down the inheritance hierarchy leads to maintenance problems, and downcasting from a base class is always illegal.
References:
- Scott Meyers, "Effective C++: 50 Specific Ways to Improve Your Programs and Design", Second Edition, Addison-Wesley, (C) 2005 Pearson Education, Inc., Chapter: "Inheritance and Object-Oriented Design", Item 39
- JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS Chapter 4.23 Type Conversions, AV Rule 178
Do you think it's a good practice for not casting down from a base class pointer to a subclass pointer? Why and When should I follow this rule?