Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 736
Mr Cold Avatar asked Mar 11 '15 13:03

Mr Cold


People also ask

Can a const reference call a non const function?

Once you have a const object, it cannot be assigned to a non-const reference or use functions that are known to be capable of changing the state of the object. This is necessary to enforce the const-ness of the object, but it means you need a way to state that a function should not make changes to an object.

Can constants be passed by reference?

Passing by const reference is the preferred way to pass around objects as a smart alternative to pass-by-value.

What is reference to const?

You can declare the test function as: int test(gadget const &g); In this case, parameter g has type “reference to const gadget .” This lets you write the call as test(x) , as if it were passing by value, but it yields the exact same performance as if it were passing by address.

What is const parameter?

A constant parameter, declared by the keyword const , is a read-only parameter. This means that we can not modify the value of the constant parameter in the function body. Using the const keyword tells the compiler that the value of that parameter will not be changed inside the function.


1 Answers

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

like image 141
juanchopanza Avatar answered Sep 24 '22 10:09

juanchopanza