TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  CON#003Checked automatically with code checker

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:

  • Avoid casting if possible.
  • If casting is required, make it explicit as much as possible, try to avoid implicit casts.
  • If casting is required on object pointers, use dynamic casting.
  • If casting is required on basic types, it is preferred to use explicit static casting.


Literature References:
Ellemtel Rule 43, adapted