const member functions can call const member functions only?
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' modifyi开发者_C百科ng the data members?
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.
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.
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
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;}
Your assertion and your analysis are both correct.
精彩评论