This rule is Obsolete | |
Synopsis: | Avoid explicit type conversions (casts) if possible |
Language: | C++ |
Severity Level: | 9 |
Category: | Conversions |
Description: |
The use of casts cannot always be prevented. One example is when working with a windows dialog using MFC. Function GetDlgItem() returns a CWnd*, while in essence it is a pointer to a control like CEdit or CButton. Here a cast is necessary. In general, casting can be necessary when interfacing with library code. Note that casting with C++ has changed a lot compared to standard "C" casting. First, using C++ a class can implement cast operators. Here the conversion between types is controlled by the class implementation and hidden to the user. The implementor of the class can take care of the correct working of the intended conversion in a centralized place. An example of this is a class that encapsulates a windows handle like MFC class CWnd. An instance of this class can be converted to the handle just by assignment. This is illustrated by the following example: CWnd Window; // C++ variant HANDLE hWnd; // normal handle hWnd = Window; // Assignment allowed since CWnd implements // implicit cast like: // operator HANDLE ( ) { return m_hWnd;}; The following rule is applied:
|
Literature References: |
Ellemtel Rule 43, adapted |