I'm writing a class that wraps a legacy C API that controls a hardware device. In a simplified example, I might have something like:
class device
{
public:
void set_request(int data) { legacy_set_req(p_device, data); }
int get_response() const { return legacy_get_rsp(p_device); }
private:
device_handle_t *const p_device;
};
The class itself has no bitwise state; therefore, I could choose to declare set_request()
as const
, and the compiler would be happy with that. However, from a semantic point-of-view, would this be the correct approach, given that it affects the observable behaviour of the object? (i.e. the encapsulated hardware device very much does have state.)
Const member functions in C++ Like member functions and member function arguments, the objects of a class can also be declared as const. an object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object.
You should mark a member function const when it does not change the visible state of the object, and should be callable on an object that is itself const .
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.
Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.
I believe that const
should reflect logical const-ness, regardless of the internal representation. Just because your object contains only a pointer to something that changes, doesn't mean all your member functions should be const
.
C++ even has the mutable
concept for internal representation that needs to change even if conceptually the object does not. The const
keyword is clearly not intended to represent "bitwise" const-ness.
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