2

Do const member functions call only const member functions?

class Transmitter{
  const static string msg;
  mutable int size;
  public: 
    void xmit() const{
    size = compute();
    cout<<msg;
  }
  private:
   int compute() const{return 5;}
};

 string const Transmitter::msg = "beep";

 int main(){
   Transmitter t;
   t.xmit();
   return EXIT_SUCCESS;
 }

If i dont make compute() a const, then the compiler complains. Is it because since a const member function is not allowed to modify members, it wont allow any calls to non-consts since it would mean that the const member function would be 'indirectly' modifying the data members?

badmaash
  • 4,775
  • 7
  • 46
  • 61

5 Answers5

5

Is it because since a const member function is not allowed to modify members, it wont allow any calls to non-consts since it would mean that the const member function would be 'indirectly' modifying the data members?

Yes.

wilx
  • 17,697
  • 6
  • 59
  • 114
3

Yes: const member functions only see the const version of the class, which means the compiler will not find any non-const members (data or functions) inside a const member function.

This effect propagates to const objects (instances) of the class, where only const members are accessible.

When applied correctly, const will allow for the programmer to check his use of the class and make sure no unwanted changes are made to any objects that shouldn't be changed.

rubenvb
  • 74,642
  • 33
  • 187
  • 332
1

Yes. When you call 'xmit()', its 'this' pointer will be const, meaning you can't then call a non-const method from there, hence 'compute()' must be const

StevieG
  • 8,639
  • 23
  • 31
1

As others have said; yes.

If there is a particular reason you want compute to be non const, for example if it uses some local cache to store calculations, then you can still call it from other functions that are declared const by declaring a const version

  private:
       int compute() const{return ( const_cast<Transmitter*>(this)->compute());}
       int compute() {return 5;}
David Sykes
  • 48,469
  • 17
  • 71
  • 80
  • Better solution for this would be to declare the cache as mutable to explicitly state it's allowed to change during const operations. – Jan Holecek Jan 06 '11 at 12:28
  • For simple caching I would agree, but for more complex functionality involving other functions this is a well established technique that is worth knowing – David Sykes Jan 06 '11 at 12:55
1

Your assertion and your analysis are both correct.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055