cppbuzz logo

Home  |  About Us  |  Contact
View Questions Upload Training Misc..

Type Casting in C++

Four type casting operators in C++ is listed below :
static_cast -> To convert non polymorphic types.
const_cast -> To add or remove the const-ness or volatile-ness type.
dynamic_cast -> To convert polymorphic types.
reinterpret_cast -> For type conversion of unrelated types.

Example of static_cast :-
int main()
int sum = 1000;
int count = 21;
double average1 = sum/count;
cout<<"Before conversion = "< double average2 = static_cast(sum)/count;
cout<<"After conversion = "< system("pause");
return 0;

Example of const_cast :-
//demonstrates const_cast
int main()
//p = 10 is a constant value, cannot be modified
const int p = 20;
cout<<"const p = ";
cout< cout<<"\nq = p + 20 = ";
cout<<(p + 20)< //The following code should generate error, because
//we try to modify the constant value...
//uncomment, recompile and re run, notice the error...
//p = 15;
//remove the const...
int r = const_cast (p);
//the value of 10 should be modified now...
cout<<"Removing the const, decrement by 1,\nNew value = "< system("pause");

Example of Dynamic cast :-
//upcast conversion using dynamic_cast
//base class
class Base1 {};
//derived class...
class Derived1:public Base1 {};
//another derived class
class Derived2:public Derived1{};
//dynamic_cast test function...
void funct1()
//instantiate an object…
Derived2* Test1 = new Derived2;
//upcasting, from derived class to base class,
//Derived1 is a direct from Base1
//making Test2 pointing to Derived1 sub-object of Test1
Derived1* Test2 = dynamic_cast(Test1); cout<<"Derived1* Test2 = dynamic_cast(Test1);"<(Test1); cout<<"\nBase1* Test3 = dynamic_cast(Test1);"< {
return 0;

Example of reinterpret_cast :-

//unsigned int pointers conversion
unsigned int* Test(int *q)
//convert int pointer to unsigned int pointer
unsigned int* code = reinterpret_cast(q);
//return the converted type data, a pointer...
return code;
int main(void)
{ //array name is a pointer... int a[10]; cout<<"int pointer unsigned int pointer"; for(int i = 0;i<=10;i++) cout<<(a+i)<<" converted to: ";
cout< system("pause");
return 0;