tecu
tecu

Reputation: 550

c++ const-ness of member functions for a C wrapper

i have an object that, at its most basic level, looks like this:

#include <X11/Xlib.h>

class x_link {
    public:
        x_link()
        {
            display_ = XOpenDisplay(NULL);
        }

        ~x_link()
        {
            XCloseDisplay(display_);
        }

        Display* display_ptr() const
        {
            return display_;
        }

    private:
        Display* display_;
};

i was wondering how "const" x_link::display_ptr() should be in a case like this.

this older question, Should member functions be “const” if they affect logical state, but not bitwise state?, gives me the impression that since my method doesn't (itself) impact either the logical or bitwise state of the object, const is the way to go.

but at the same time, providing the Display* allows users to break the object (for example, by calling XCloseDisplay() themselves), which would be a very non-const thing to do.

any thoughts?

Upvotes: 4

Views: 246

Answers (1)

Matt Kimberling
Matt Kimberling

Reputation: 93

This class looks like a simple wrapper class whose purpose is primarily to wrap a C interface. In that case I advise you to not complicate your program by using const at all.

I reserve the use of const for clear cut cases where an object or function is read-only.

Const is one of the many C++ features that often trick programmers into making their programs unnecessarily complicated.

Upvotes: 1

Related Questions