const.cpp
#include <iostream>
using namespace std;
 
 
//
// CONST DEMO
//
 
void konstConstantDemo() {
    //const int a, b = 0; // error, uninitialized const 'a'
    const int numMonthsInYear = 12;
    cout << "Number of months in year: " << numMonthsInYear << endl;
    //numMonthsInYear = 13;   // error, assignment of read-only variable
}
 
char* konstReturnValueDemo() {
    return "Unmodifiable string";
}
const char* konstReturnValueDemo2() {
    return "Unmodifiable string";
}
 
void konstParamDemo(const int* pParam) {
    //*pParam = 1; // error, assignment of read-only location
}
 
class CMouse {
   unsigned int m_size;
public:
   void setSize(unsigned int newSize) {
       m_size = newSize;
   }
   int getSize() const {
       return m_size;
   }
};
 
void konstFunctionDemo() {
    CMouse mouse1;
    //const CMouse mouse2;    // error: uninitilized const mouse2
    const CMouse* pMouse2 = &mouse1;
 
    mouse1.getSize() ;
    mouse1.setSize(10);
    cout << pMouse2->getSize() << endl;
 
    // Let's try to call non-constant method of constant object
    //pMouse2->setSize(10);    // error: no matching function for call
 
}
 
int main() {
    //konstConstantDemo();
 
    //char* value = konstReturnValueDemo();
    //value[1] = 'x';         // read-only memory write - problem
 
    //char* value2 = konstReturnValueDemo2(); // error: invalid conversion
 
    //konstFunctionDemo();
 
    return 0;
}
QR Code
QR Code public:pb161_2010_c1 (generated for current page)