Returning a non-constant link from a const member function

Why is a reference returned to a member-pointer variable, but not another? I know that a member function constshould only return links const, but why doesn't this look like pointers?

class MyClass
{
  private:
    int * a;
    int b;
  public:
    MyClass() { a = new int; }
    ~MyClass() { delete a; }

    int & geta(void) const { return *a; } // good?
    int & getb(void) const { return b; }  // obviously bad
};

int main(void)
{
  MyClass m;

  m.geta() = 5;  //works????
  m.getb() = 7;  //doesn't compile

  return 0;
}
+3
source share
2 answers
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; }  // obviously bad

In a const function, each data element becomes const in such a way that it cannot be changed . intbecomes const int, int *becomes int * const, etc.

Since the type ain your first function becomes int * const, not const int *, therefore, you can change the data (which can be changed):

  m.geta() = 5;  //works, as the data is modifiable

The difference between: const int*and int * const.

  • const int* , const, , , const.
  • int * const , const, , , const.

const int &, b const int. int &, (. this), , main(), . :

 const int & getb(void) const { return b; }  

!.

+15

a int * const a;. a ( , ), const. , a , .

, . const const.

+6

Source: https://habr.com/ru/post/1793337/


All Articles