Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Jun 26, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

New cast operators

C++ still supports C-style type casting in the form of '(T) e' as in:
 	int i = (int) 7.333;
Nonetheless, this casting notation is not recommended. What is amiss with C-style cast? First of all, the () operator is already used excessively in the language: in functions calls; in precedence re-ordering of expressions; in for, while, do and if statements; in operator overloading and other syntactic constructs. Secondly, the C-style cast is too general: it carries out different actions in different contexts - so different indeed, that one can hardly tell which is which; it may perform an innocuous, standard cast like converting an int to a float, it can convert non-related types such as integers into pointers (highly non-portable and even dangerous); it can be used to remove only the const and/or volatile quality of an object and, in earlier stages of the language, it would even perform a dynamic cast! For these reasons, new cast operators were added to the language. They are intended to replace the C-style cast, and it is estimated that the latter will become deprecated in the future. The new cast operators are:
	static_cast  (from); //performs a relatively safe and portable cast
	const_cast  (from); //removes the const and/or volatile quality of and object solely 
	reinterpret_cast (from) //in low level conversions such as casting a function pointer to void*
	dynamic_cast (from)//performs a cast during runtime rather than compile time
These new operators are more explicit in their intended purpose. They are more meaningful (a name like dynamic_cast, for example, warns its users about its incurred runtime overhead) and most importantly: they are safer since they give the compiler a chance to detect mistakes such as trying to modify an object's type when the user's intention was only to convert it into a non-const one.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date