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

 Home / General Programming / const something foo() {} 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.

May 10, 2005, 03:20 AM

This might be a stupid question but can anybody tell me what the 'const' in the following declaration is good for ?

const something foo()


Chad Austin

May 10, 2005, 03:28 AM

Let's say you have a function foo that returns a std::string. Technically it's legal to do something like:

  2. #include <string>
  4. const std::string foo() {
  5.     return "foo";
  6. }
  8. int main() {
  9.     foo()[1] = 'a';
  10. }

There aren't too many situations where that's meaningful, so you may wish to explicitly mark the return value as const. Note that the const modifier only makes sense for certain types of objects. The result of 'int bar()' is implicitly const (rather, it's an r-value), and some compilers will warn if you declare 'const int bar()'.



May 10, 2005, 04:01 AM

Hey, thanks a lot.
I just asked because I stumbled over some older code from a colleague here, who declared most every function in his classes like that:

const int foo1() {}
const double foo2 () {}

So I was a little confused since I never saw it used like that before (on obviously now, it makes not so much sense ... )

Thanks again.



May 10, 2005, 04:29 AM

Maybe what he meant was

  2. int foo1() const {}
  3. double foo2 () const {}

which says foo1() and foo2() won't modify the object for which they are called.

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