+ 7

Using const in member functions C++

Reading a C++ book, I found this little code: Std::string getName() const {} The books says that the declaration of the member function as constant it's because in the process of returning the name the function does no, and should not modify the object in which it's called. So... Each object shouldn't be modify? When do I need to use const? Also, I have been using this, putting the const inside the parameter Void someFunction (const string & A) But now, I'm not sure which one I should use: Void someFunction (const string & A) const Void someFunction (const string &A) Void someFunction (string&A) const Which one should I use? I'm so confused, which one is the correct? What are the differences between put const inside the parameter, put const outside or put both, inside parameter and outside?

29th Dec 2018, 4:00 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
2 Réponses
+ 18
The const keyword after a function declaration is used only with classes, to indicate that the particular method (member function) is not allowed to modify the members of the class. As for the const reference (const type& syntax), that is usable in any function or method, and is used to prevent excessive memory allocations (You use the same variable in the function that you passed instead of making a copy.) The const keyword allows for passing rvalues as they are unmodifiable. It is similar to a const variable. When you define a class and instantiate a constant object, you are not allowed to use non-const members. Only those members marked const can be used. That is where you need const on a function definition. The first version is not useful, as the passed object is already const. Here is an example: class Example { int n; public: int get() const { return n; } void set(int k) { n=k; } }; int main() { Example e; const Example ce; e.set(5); // Ok. ce.set(6); // Error! }
29th Dec 2018, 5:09 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
Thank you so much Kinshuk Vasisht !!!!
30th Dec 2018, 6:32 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar