C++ : Development const cast Demonstrates const_cast

Started by dhilipkumar, Mar 07, 2009, 08:53 PM

Previous topic - Next topic

dhilipkumar

C++ : Development const cast  Demonstrates const_cast


#include <iostream>
using namespace std;
void sqrval(const int *val)
{
  int *p;
                               
  p = const_cast<int *> (val); // cast away const-ness.
  *p = *val * *val;            // now, modify object through v
}
int main()
{
  int x = 10;
  cout << "x before call: " << x << endl;
  sqrval(&x);
  cout << "x after call: " << x << endl;
  return 0;
}

           

dhilipkumar

Demonstrate const_cast.


#include <iostream>
using namespace std;

void sqrval(const int *val)
{
  int *p;

 
  p = const_cast<int *> (val);               // cast away const-ness.

  *p = *val * *val;                          // now, modify object through v
}

int main()
{
  int x = 22;

  cout << "x before call: " << x << endl;
  sqrval(&x);
  cout << "x after call: " << x << endl;

  return 0;
}




dhilipkumar

Use const_cast on a const reference


Use const_cast on a const reference


#include <iostream>
using namespace std;

void sqrval(const int &val)
{
 
  const_cast<int &> (val) = val * val;     // cast away const on val
}

int main()
{
  int x = 22;

  cout << "x before call: " << x << endl;
  sqrval(x);
  cout << "x after call: " << x << endl;

  return 0;
}


           

dhilipkumar

const_cast Demo


#include <iostream>
using namespace std;

void f(const double &i)
{
  double &v = const_cast<double &> (i);

  v = 100.0;
}


int main()
{
  double x = 98.6;

  cout << x << endl;
  f(x);
  cout << x << endl;

  return 0;
}