Who`s Afraid to Be Const Correct? Take Your Object`s Bits Literally - Bitwise Constness
(Page 3 of 5 )
I just wanted to get you into a bitwise state of mind because the other problem in the class lies with the ‘char* GetLabel() const’ declaration. Since this function is const, we cannot change the contents of an instantiated MyClass object, right? Yes… well… sort of… it depends on how you look at it:
MyClass const *label3 = new MyClass(“label3”);
(void)sprintf(label3->GetLabel(), “changed”);
Yes, your compiler will not choke on this, and the content of m_pLabel in the object ‘label3’ is set to ‘changed’! Strictly (and bitwise) speaking, we haven’t changed anything in the ‘label3’ object; its data members remain the same… just not conceptually. The pointer that holds the address to the string is the actual data member and not the memory pointed at. We didn’t change the address; the compiler won’t complain!
This is called ‘bitwise’ constness and just as with ‘bitwise copy construction’ you should pay extra attention when you see that a class has a pointer as a member. The following function declaration would implement our real intention:
char const* GetLabel() const { return m_pLabel; }
But here it is ‘char const*’ that prevents you from making changes to m_pLabel, and not the fact that the member function is constant!
In case you are wondering whether it is possible to add ‘private: int m_Value’ to the interface of the class along with the following function:
int* GetValue() const { return &m_Value; }
No! Your compiler will detect that m_Value should be treated as const in this case because it is a data member. There is a big difference between not being able to modify the address to a piece of memory and not being able to modify the memory itself.
Conceptually you would consider the memory pointed at to be part of the object as well… but bitwise it is not. Remember that the restrictions on one (not being able to modify the variable holding an address to a piece of memory) don’t automatically apply to the other, so you probably want to restrict access to the memory itself as well.
Next: Make Your Interface Conceptually Const. >>
More C++ Articles
More By J. Nakamura