C++ Programming/Programming Languages/Paradigms/Encapsulation

From Wikibooks, open books for an open world
Jump to: navigation, search

Encapsulation[edit]

Encapsulation (also known as information hiding) is a concept commonly used on large software projects to allow for extensibility. The principal behind encapsulation is to hide the inner workings of a class from the code that uses the class, only exposing the essentials.

Why Bother?[edit]

Team development projects often split up tasks. Designing clean, easy to understand interfaces makes code easier to understand. If a data member of a class written by Team A is used by Team B, and the class changes a way the data member works, it can break compatibility with Team B's code. Not only is maintaining data members of a class very difficult, it can also be quite confusing to clients. The interface of an encapsulated class is like a contract to clients, stating what it is capable of doing. The client shouldn't care how it is done, in fact it can be upgraded in the future, as long as it complies with the same interface.

Implementation[edit]

To completely encapsulate a class, all data members of the class must be private. In designing the class, it must be determined what data must be accessible, and what can be kept completely hidden. The data to be made public will require "accessor functions," which can allow data to be read or stored in private data members.

Example[edit]

//Non-encapsulated class
class raceCar {
    public:
        void drive()
        int pos;
        int speed;
};
//Encapsulated class
class raceCar {
    public:
        void drive()
 
        void setSpeed(int s) {m_speed = s;}
        int speed()          {return m_speed;}
 
        int position()       {return m_pos;}
    private:
        int m_pos;
        int m_speed;
};