Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement getters and setters in header file [closed]

Tags:

c++

getter

setter

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_;
};
like image 652
Maxence Henneron Avatar asked Apr 29 '14 13:04

Maxence Henneron


People also ask

Should setters and getters be public?

Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.

Are getters and setters encapsulated?

Having getters and setters does not in itself break encapsulation. What does break encapsulation is having a getter and a setter for every data member (every field, in java lingo). That is one step away from making all data members public.

Do getters and setters go inside the constructor?

You should not call getters and setters from the constructor. A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will. The only way to guarantee initialising the fields is to assign them.

Where do you put getters and setters?

The Java coding convention states that methods (getters and setters are methods) should be after constructors declarations. It just a convention and it exists to make code easier to read in general.


Video Answer


1 Answers

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.

like image 101
doron Avatar answered Sep 22 '22 22:09

doron