Const Cast

/////////////////////////////////////
// ConstCastDemo.cpp: demonstrates const_cast operator
// Author: Yu Zhang
// Org: Syracuse University
// Contact: 315-314-0228
/////////////////////////////////////

/*

 Const cast:
-------------
Casts away constness, used when you know a function call won't
change invoking object or parameter, but the compiler does not
know that.

 nonConstType& nct = const_cast<nonconstType&>(ct);
 nonConstFunction(nct);

*/

#include <iostream>
using namespace std;

void PrintNumber(int& i){
  cout<<i<<endl;
}

void LazyPrinter(const int &j){
  cout<<"I am lazy, let my dude print the number\n";
  //const cast j, cast away constness, so that non-const function PrintNumber
  //could accept this non-cast parameter
  //otherwise, compilation would fail
  int &nonConstJ = const_cast<int&>(j);
  PrintNumber(nonConstJ);

}

int main(){
  int i=9;
  LazyPrinter(i);
  return 0;
}

/*
Error Report(without const cast):

ConstCastDemo.cpp: In function ‘void LazyPrinter(const int&)’:
ConstCastDemo.cpp:30: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’
ConstCastDemo.cpp:24: error: in passing argument 1 of ‘void PrintNumber(int&)’
*/

Comments

Popular Posts