Cast – Converting a variable to a different type in an operation (int*)

Although necessary at times, casts are inherently dangerous (becuase you don’t get a compiler warning that a potentially bad conversion will occur). It is more nomral to just allow C++ to do its normal automatic conversion which will typially involve increasing the size of everything to match the largest variable, and then downsizing if necessary to fit the result in the destination variable. However there are times when you’ll want to specify a conversion.

These are the explicit conversions available in C++:


Use for any type conversion that we want to tell the compiler to do and to tell it that we know we want it so there’s no need to warn us about it happening (this type of cast is considered OK to use occasionally)


Supports the run time identification of objects addressed by a pointer of reference (this type of cast is considered OK to use occasionally)


Use to cast away const’ness (e.g. great when calling a function that only takes a variable but you want to supply a constant). (Using this almost always indicates a design flaw – it should not be necessary)


Performs a low level reintrepretation of the bit pattern of its operands – machine dependant. (This cast is considered hazardous for bugs – don’t use)

The standard C cast, e.g. (int*) is equivalent to const_cast, static_cast or reinterpret_cast depending on the types involved. C++ introduced these named casts to give a more finely tuned tool when casts are necessary. The C casts are supports under C++ to provide backwards compatibility.

Every time you use a cast you should think hard about wether you can acheive the same result a different way. Not using them helps reduce bugs.

Example usage:

	i_val *= static_cast(d_dal);		//Converts d_val to int

	const char *pc_str;
	char *pc = string_copy(const_cast(pc_str);	//Converts d_val to int
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.


Your email address will not be published. Required fields are marked *