Friday, May 26, 2017

Calling a method on constant C++

Why does the error below happen? 

member function 'SetMethodX’ not viable: 'this' argument has type 'const webrtc::ClassY’, but function is not marked const
In my case, the ClassY was constant and using that it was trying to call SetMethodX which was defined to be not constant.

To be able to call a function on a const object, you need to promise the compiler that the function will not modify the object. To do that, you mark the function with the keyword const after its argument list. For example, to make getDimension a const member function, you would change it to:

const ULL getDimension() const { return dimension; }
(Note that the const in the return type will have absolutely no effect, so you should get rid of it)

references:

No comments:

Post a Comment