1. Home
  2. Computing & Technology
  3. C / C++ / C#
David Bolton
David's C / C++ / C# Blog

By David Bolton, About.com Guide to C / C++ / C#

A C++ Exception to the Rules

Friday November 13, 2009
You can't modify a const can you? Well technically no, but there is one place (before a constructor) where you can. If the parameter used to construct an instance of the Example class is 0 then it allocates an 80 char string and frees it in the destructor.

#include <iostream>

class Example
{
private:
    const char * ptr;
    const bool freeable;
public:
Example(const char * optional):
    ptr( optional ? optional : new char [80]),
    freeable( optional ? false : true ) {}
~Example( ) { if (freeable) delete[] ptr; }
void ViewState(char ID) {
    if (freeable)
        std::cout << ID << " is Freeable" << std::endl;
    else
        std::cout << ID << " is not Freeable" << std::endl;
    }
};


int main(int argc, char * argv[])
{
    Example S(0) ;
    Example T("Hello World") ;
    S.ViewState('S') ;
    T.ViewState('T') ;
return 0;
}

So S is freeable, T is not.

Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

©2009 About.com, a part of The New York Times Company.

All rights reserved.