Implement getters and setters in header file

Maxence Henneron picture Maxence Henneron · Apr 29, 2014 · Viewed 14k times · Source

I have a simple question, is it a good practise to implement getters and setters in the header file, like this ?

class WebsocketSession : public boost::enable_shared_from_this<WebsocketSession>{
public:
    WebsocketSession(boost::asio::io_service& io_service, WebsocketServer& server);

    tcp::socket& getSocket() { return socket_; } // <---  This
private:
    tcp::socket socket_;
    WebsocketServer& server_;
};

Answer

doron picture doron · Apr 29, 2014

Advantage

The getters and setters will be inlined so they will have no function overhead.

Disadvantage

You will be unable to make any changes to your getter and setter without having to recompile all code using your class. This is especially bad when the implementation of your class lies in a different DLL or .so file.

I personally do not like placing getters and setters in the header files.