Cannot call a method of const reference parameter in C++

11,127

You can't call non-const member functions via const references. You can fix this by making the member function const:

void method() const {};
              ^^^^^

This indicates that calling the member does not mutate the object it is called on*

* Conceptually. In practice it can mutate members marked mutable

Share:
11,127

Related videos on Youtube

Mr Cold
Author by

Mr Cold

Updated on June 05, 2022

Comments

  • Mr Cold
    Mr Cold almost 2 years
    class A
    {
    public:
        A(){};
        ~A(){};
        void method(){};
    
    };
    
    void call(const A &a)
    {
        a.method();   // I cannot call this method here if I use "const" but I can call it if not using "const"
    }
    
    int main()
    {
        A a;
        call(a);
        return 0;
    }
    

    In this case, the error is: "passing const A as this argument of void A::method() discards qualifiers [-fpermissive]|"

    In function call, if I use const, I get the error, but if I get rid of it, it works.

    Can anyone explain it for me?

    • Lightness Races in Orbit
      Lightness Races in Orbit about 9 years
      What do you think the const does?
    • Lightness Races in Orbit
      Lightness Races in Orbit about 9 years
      @MrCold: The only reason that code doesn't work is because you have a bug in the operator[] that you randomly added and that has nothing to do with this question. Try to change just one thing at a time when you are trying to solve problems. If you'd only added the const to method(), you'd have seen that it works fine.
  • Mr Cold
    Mr Cold about 9 years
    Thank you for your answer but this as I see this rule does not work with overloading operator [] as follow: pastebin.com/1mKek7pM Can you explain more?
  • juanchopanza
    juanchopanza about 9 years
    @MrCold What do you mean "this rule doesn't work"? Do you mean it doesn't compile? That is because you are returning a non-const reference to a data member via a const reference to the object.
  • juanchopanza
    juanchopanza about 9 years
    @MrCold In other words, the const overload should return a const reference (or a value): const int& operator [] (int i) const {return num;}. You can also add a non-const overload for when you want to be able to modify the data member: int& operator [] (int i) {return num;}
  • Mr Cold
    Mr Cold about 9 years
    Oh, i got it. Thank you very much for your explanation :)