Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should member functions be "const" if they affect logical state, but not bitwise state?

Tags:

c++

constants

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.)

like image 655
Oliver Charlesworth Avatar asked Mar 06 '11 02:03

Oliver Charlesworth


People also ask

Can a member function be const?

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.

What is the best time to mark a member function as constant?

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 .

Why can't you assign a const reference to a non-const reference?

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.

What does a const keyword after the parameters for a member function mean?

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.


1 Answers

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.

like image 194
Greg Hewgill Avatar answered Sep 23 '22 02:09

Greg Hewgill