• Fun with C++

    From Nightfox to All on Fri Nov 22 19:34:54 2013
    Nasty fun things to do in C++ (AKA Things not to do in C++, AKA How to shoot yourself in the foot in C++):

    Do you ever need to access private data members/functions in a class? Are you frustrated that you aren't allowed to do that? No problem - Just put this at the top of your source file:
    #define private public
    By re-defining private as public, you'll be able to access the private members of an object!

    Do you think references are safe? Think again! Consider this code: ////////////////////////////////
    int *dynamicInt = new int(3);
    int& intRef(*dynamicInt);
    cout << "intRef (1): " << intRef << endl;
    delete dynamicInt;
    cout << "intRef (2): " << intRef << endl;
    ////////////////////////////////
    After executing 'delete dynamicInt;', your program is likely to crash when you try to use intRef again!

    Do you think 'const' always guarantees constness? Think again! The const_cast operator can be used to remove constness. Consider this function:
    void someFunc(const string& aString)
    {
    string& str(const_cast<string&>(aString));
    str = "Hello";
    }
    Now, the value of aString has been changed by the function!

    These are just a few of the many fun things you can get away with in C++ and potentially shoot yourself in the foot!

    Nightfox