Complete listing of Variables06.cpp, Listing 6
/*File: Variables06.cpp This C++ program illustrates constants. The program shows that an attempt to modify the value of a const variable after it is initialized results in a compiler error. The program displays the following output on the screen when the offending statement is disabled by turning it into a comment: 3.14159 ************************************************/ #include <iostream> using namespace std; class Variables06{ public: static void classMain(){ //Instantiate an object in dynamic memory // and save its reference in a pointer // variable. Variables06* ptrToObject = new Variables06(); //Invoke an instance function on the object. ptrToObject -> doSomething(); }//End classMain function //-------------------------------------------// //An instance function of the Variables06 class void doSomething(){ //Declare and initialize a constant. const double pi = 3.14159; //The following attempt to change the value // of a constant results in a compiler error. //pi = 16.5; cout << pi << endl; }//end doSomething function };//End Variables06 class //---------------------------------------------// int main(){ Variables06::classMain(); return 0; }//end main Listing 6 |