New cast operators

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.

See also  How HealthStream Learning Center Supports Healthcare Education and Compliance

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist