Monday 27 April 2009

Using Const Cast

The following is an example to use the const_cast in C++.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example shows how to use const_cast
#include<iostream>

using namespace
std;

void
func1(int *x)
{

cout<<"\n2. xyz = "<<*x<<endl;

//Possible but its like cheating
(*x)++;
}



void
func2(const int *x)
{

cout<<"\n4. xyz = "<<*x<<endl;
//(*x)++; //Not possible to do this, compile time error
}

int
main()
{

int
xyz = 22;
const
int *abc = &xyz;
cout<<"\n1. xyz = "<<xyz<<endl;
//func1(abc); //Not possible to call, need a cast, compile time error
//Use const_cast only when you trust a function to not change the value
func1(const_cast<int *>(abc)); //Cast the constness of abc away
cout<<"\n3. xyz = "<<xyz<<endl;
func2(abc);
cout<<"\n5. xyz = "<<xyz<<endl;
}



The output of the program is as follows:

No comments:

Post a Comment