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++:

static_cast

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)

dynamic_cast

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

const_cast

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)

reinterpret_cast

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
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.