C++
  Home arrow C++ arrow Page 3 - Const Correctness in C++
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Const Correctness in C++
By: Gabor Bernat
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2008-10-28

    Table of Contents:
  • Const Correctness in C++
  • Constant Variables
  • Const in Functions and in Classes
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Const Correctness in C++ - Const in Functions and in Classes


    (Page 3 of 4 )

    Another observation we need to make is that C++ can resolve automatically the conversion of a variable from non-const to const, but not the reverse. This will allow us to call functions that take const parameters with non-const variables. Also, in this way eventual programming design errors can be eliminated.

    Look at the code snippet below as it presents a brief example of how this technique will be used in classes. Explanations follow:

    class point

    {

    public:

    int& x () const;

    const int& x () const;

    int& y () const;

    const int& y () const;

    void setNewValues (const int& newX, const int& newY);

    bool isEqual (const int* const newX,

    const int* const newY)const;

     

    private:

    int x;

    int y;

    mutable string errorMessage;

     

    }

    Implementation of a few:

    int& point::x () const

    {

    return x;

    }

     

    bool point:: isEqual (const int* const newX,

    const int* const newY) const

    {

    if( !newX && !newY)

    errorMessage = ("Invalid pointers in an isEqual");

     

    return *newX = x() && *newY == y();

    }

     

    Now here we have almost all of what you should know about const correctness in classes. The class represents a point simulation in 2D. First, I will explain why we are making the two intern variables private and after that returning const references to it. The explanation is quite simple. Read below!

    Have you ever faced a situation where you just observed that a variable changed its value and you have one idea where to search for the modification in the code? In fact anyone could easily access the class's members from anywhere, so now you should debug all of the code and find where the mistake was made. You don't need to do that with this approach; now we can put a break point in the x function, and at every little modification this modification must be called. If we use this approach in the class also, it will result in easily debuggable code, less time wasted, and more efficiency.

    But to switch back to our subject, probably you observed that we have written const after a few functions. If you look closer you'll also detect that this is true only for functions where no modifications are made for the members. And this is what we mean by const functions in classes.

    You guarantee (and the compiler will make sure of it) that not a single modification can or will be made for the members of the class. At least, you do this at first glance. Here is the exception: the mutable keyword. The mutable is what defies all this. Any member declared mutable can be modified within a const function. This is perfect if we want to implement, for example, an error reporting string in the class; errors could occur in a const function also, after all. Consider the isEqual function shown earlier. 

    Bear in mind that you can't call any of the non-const functions inside of a function like this. All functions called within must be const to maintain the rule that not a single one (expecting the mutable ones, but that's the wonder of it) will have different values compared to the start at the end of calling the respective task.

    At this moment you should also comprehend why we wrote two x() functions. This way C++ will complete const overloads, and whenever needed, it's going to call the const one, which is only for an equality check. The const reference ensures that the type won't be messed with anywhere during the call, and also the non-const type will still let us modify the members anywhere in the program.

    You may have some situations when you know that a function won't change the value of a const type, but you can't call it, as the function isn't made const. For these special cases, use the const_cast. The cast lets you create a temporary non-const type to it, so you can force the function to call it. Be conscious, though, that when the members are going to be modified, the result can be undefined.

    If you know a little STL you've probably figured out by now what the const_iterator means. Yes, you are right. This type of iterator makes const the type at which it's pointing, and due to this no modification can be made to the members (not to the iterator, just to what it is pointing, unless you declared the iterator itself as const). Use this type of iterator whenever you need to see the members in a container in a const function but are now willing to modify a single member.

    More C++ Articles
    More By Gabor Bernat


     

    C++ ARTICLES

    - More Tricks to Gain Speed in Programming Con...
    - Easy and Efficient Programming for Contests
    - Preparing For Programming Contests
    - Programming Contests: Why Bother?
    - Polymorphism in C++
    - Overview of Virtual Functions
    - Inheritance in C++
    - Extending the Basic Streams in C++
    - Using Stringstreams in C++
    - Custom Stream Manipulation in C++
    - General Stream Manipulation in C++
    - Serialize Your Class into Streams in C++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT