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?
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.
Passing by const reference is the preferred way to pass around objects as a smart alternative to pass-by-value.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With