Encapsulation in C++

05 min read

Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data. Data encapsulation led to the important OOP concept of data hiding. Generally, encapsulation can also be defined as wrapping up of data and information under a single unit.

Example:

#include <iostream>
using namespace std;

class Add
{ public: Add(int i = 0)
{ total = i; } void addNum(int number)
{ total += number; } int getTotal()
{ return total; }; private: int total; }; int main()
{ Add a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0; }

 

Output

Total 60

 

Above class adds the numbers together, and returns the sum of them. The public members addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world but is needed for the class to operate properly.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error