Monday, March 31, 2008

const_cast casting operator

Today I want to explain about the const_cast C++ operator.

const_cast is a new operator introduced in C++, for casting purposes. This casting operator can be used, either to introduce or remove const-ness from a expression.

The usage format of this operator is as follows,

const_cast <type> (expression)

example: 01
Skill Level: Intermediate

In this program, I will explain how const_cast can be used to remove const-ness from a variable/function parameter.

consider following program..

#include <iostream>

void
square(int &number)
{

number *= 2;
}


int
main(int argc, char *argv[])
{

int
num = 10;

std::cout<<"\nThe initial value of the number is "<<num<<std::endl;

// call square function
square(num);

std::cout<<"\nThe new value of num is "<<num<<std::endl;

return
0;
}


In this program uses the reference variable to return the square of the input data.

Let's modify this program. Lets make the function square to take a constant reference.

No comments: