0

A have the following code:

struct abc {
    abc(int a) : a(a) {}
    
     int operator [] (int t) {
         return t;
     }
    
    int a;
};

int main()
{
    abc const abc1(25);
    int c = abc1[75];

    return 0;
}

The error is "passing ‘const abc’ as ‘this’ argument discards qualifiers [-fpermissive]". I dont understand why this error appears? I do not change the fields of the const structure.

If i write abc abc1(25); instead of abc const abc1(25); it's no error.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 5
    Make your method `const` -> `int operator [] (int t) const {return t;}`. – Quimby Jan 31 '23 at 08:28
  • Imagine that you don't have access to the code of `operator[]`. Can you tell whether it changes anything or not? – molbdnilo Jan 31 '23 at 08:33
  • In C++, a class can specify two APIs commingled together. One is the `const` API, and the other is the *mutable* API. A non-const object can access the `const` API and the *mutable* API. A `const` object can only access the `const` API. – Eljay Jan 31 '23 at 12:14

0 Answers0