Home arrow C++ Programming arrow C++ Pitfalls

Language Translator

Hacking Zone

Hacking Tools
Attacking

Configure Windows

Windows Configuration

Novels

Mix Novels

Human Personality

Body Language
C++ Pitfalls PDF Print E-mail
Written by Scott Wheeler   
Thursday, 10 January 2008
Article Index
C++ Pitfalls
Page 2
Page 3
Page 4
Page 5
Page 6
 

mutable Class Members

We discussed const members earlier and like many things there are exceptions to the rule -- in this case the mutable keyword is the key to making exceptions to const-ness.

There are a number of possible uses of the mutable keyword, but most of them are obscure and rarely used. The most often usage of mutable is to specifically declare that a class member variable may be changed by a const method.

This is most often used in cases such as delayed initialization or similar. Take for example:

class Foo
{
public:
Foo() : m_object( 0 ) // initalize to null
{

}
~Foo()
{
delete m_object;
}

const Object *object() const
{
if( !m_object )
m_object = new Object;

return m_object;
}

private:
mutable Object *m_object;
};

In the example above we have an accessor which convention says should be const. However in this case we're assuming that we never want to return an uninitialized value, so because the member variable has been marked as being mutable we're able to modify it even in a const method.

If m_object were not marked as mutable then the compiler would give an error indicating that we are not allowed to change the value of a class member variable in a const method.

Note: Like exceptions to most rules, the mutable keyword exists for a reason, but should not be overused. If you find that you have marked a significant number of the member variables in your class as mutable you should probably consider whether or not the design really makes sense.





Digg!Reddit!Del.icio.us!Google!Live!Facebook!Slashdot!Netscape!Technorati!StumbleUpon!Spurl!Wists!Simpy!Newsvine!Blinklist!Furl!Fark!Blogmarks!Yahoo!Smarking!Netvouz!Shadows!RawSugar!Ma.gnolia!PlugIM!Squidoo!BlogMemes!FeedMeLinks!BlinkBits!Tailrank!linkaGoGo!Free social bookmarking plugins and extensions for Joomla! websites! title=
Comments
Add NewSearch
Only registered users can write comments!

Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved.



Last Updated ( Thursday, 10 January 2008 )
 
< Prev   Next >
Your Ad Here

Donate us!!

Enter Amount:

RSS socialnet

Add to MyYahoo!
Subscribe in NewsGator Online
Add to Newsburst
Add to Google
Add to My AOL
Add to Pluck
Subscribe in FeedLounge
Add to Windows Live
Add to NetVibes
Subscribe in Rojo
Subscribe in Bloglines
Add to MyMSN
Add to Plusmo for your cellphone
Add to PageFlakes
Add to Technorati
Add to BlinkBits