Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const at the end of function declaration in C++ [duplicate]

Possible Duplicate:
Meaning of “const” last in a C++ method declaration?

In the below function declaration,

const char* c_str ( ) const;  

what does the second const do ?

like image 413
ango Avatar asked Nov 17 '25 20:11

ango


1 Answers

It means the method is a "const method" A call to such a method cannot change any of the instance's data (with the exception of mutable data members) and can only call other const methods.

Const methods can be called on const or non-const instances, but non-const methods can only be called on non-const instances.

struct Foo {
  void bar() const {}
  void boo() {}
};

Foo f0;
f0.bar(); // OK
fo.boo(); // OK

const Foo f1;
f1.bar(); // OK
f1.boo(); // Error!
like image 126
juanchopanza Avatar answered Nov 19 '25 10:11

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!