Using C ++ const in class methods

Possible duplicates:
What const is

used here. Using 'const' in class functions

Hi everyone,
I keep making mistakes in using const with class methods and variables. For example, sometimes I fix problems with

const int myfunc(const int &obj) const { }

several times I feel that I do not need const at the end, since the parameter is already const, so I don’t understand why I should apply this fact by adding const to the end.

0
source share
3 answers

const int myfunc(const int &obj) const { }

  • const , . , int , .
  • const , obj . , .
  • const , myfunc . , - , .

№ 3, :

class MyClass
{
    void Func1()       { ... }  // non-const member function
    void Func2() const { ... }  //     const member function
};

MyClass c1;        // non-const object
const MyClass c2;  //     const object

c1.Func1();  // fine...non-const function on non-const object
c1.Func2();  // fine...    const function on non-const object
c2.Func1();  // oops...non-const function on     const object (compiler error)
c2.Func2();  // fine...    const function on     const object
+4
+3

The constant at the end indicates the constant of the member variable relative to the class. It indicates that it does not change any state of the class. The constant at the beginning indicates a const'ness of type int.

0
source

All Articles