Not logged in, Join Here! or Log In Below:  
 
News Articles Search    
 

 Home / General Programming / A strange const usage (C++) Account Manager
 
Archive Notice: This thread is old and no longer active. It is here for reference purposes. This thread was created on an older version of the flipcode forums, before the site closed in 2005. Please keep that in mind as you view this thread, as many of the topics and opinions may be outdated.
 
Marmakoide

April 18, 2005, 06:39 AM

I was reading a code, and I see

  1.  
  2. LinearTransformation3d invert() const;
  3.  


What is the difference with :
  1.  
  2. LinearTransformation3d invert();
  3.  

 
Racy

April 18, 2005, 07:28 AM

It means that the member function invert() does not change the object in any way when it is called. Sometimes it is important for the compiler to know that so it is good practice to set a member function to const when it does not change the object.

 
Chris

April 18, 2005, 01:10 PM

It's not only important to the compiler. Try this:

  1.  
  2. const LinearTransformation3d foo;
  3.  
  4. foo.invert ( );
  5.  


It'll give you an error saying it cannot call the non-const member function invert on const instance foo, if you declared invert() without the const suffix.

It makes a promise that invert() does not alter foo in any way, and thus can be safely called on a const instance.

 
juhnu

April 19, 2005, 05:03 AM

if you want to keep methods semanticaly const, but update some internal variable (for caching data or some other reason) you can either use const_cast or mutable modifier for the parameters. However, the const_cast should be used only as a last resort if everything else fails and you need to hack something in..

  1.  
  2. struct Hello {
  3.   mutable int batman;
  4.    int robin;
  5.  
  6.    void Hello() const {
  7.       batman=0; //this is ok
  8.       const_cast<Hello*>(this)->batman=0; //this is ok too
  9.       robin=0; //compile time error
  10.    }
  11. };
  12.  
  13.  



juhani

 
This thread contains 4 messages.
 
 
Hosting by Solid Eight Studios, maker of PhotoTangler Collage Maker.