Data abstraction provides only essential information to the outside world and hiding their background details. Abstraction is one of the main concepts of the Object Oriented Programming. A class represents an “entity” that can communicate with other classes or functions. But, class can hide information about its data and behavior. It can be done by using private
data members and functions. Class should provide access to only necessary information which is useful outside the class and we should hide its internal representation.
Look on the following line:
cout << "Hello!" << endl;
You know that this line will output “Hello” in console using object cout
of class ostream
. The cout
object is abstract to us. We don’t know anything about internal representation of ostream
class. We use it for output but there is no need to know how it interacts with Windows operating system.
Data abstraction increases the effectiveness of programs. If you have a car and car gets start by putting the key. There is no need to understand how fuel comes from the tank inside the engine of a car and how it catches fire using a spark plug and how wheels rotate after combustion of fuel inside engine. All these details are abstracted from you when you drive a car. Because of these abstractions you can effectively drive a car because only essential information are visible to you that make you drive easily.
To make member variables and functions visible to us outside the class, we should use public
access specifiers instead of private
.
A class communicates with the outer world by using public
data member functions. These member functions are often called interface of a class. When you design a class, you should separate the implementation of a class with its interface. This will give you a possibility to easily change the behavior of the class without changing the interface code.
Look at the following example of Abstraction:
class myStack { //interface of class myStack //this is only accessible for user public: //allocate memory for stack myStack(int _size = 50) { size = _size; stack = new int[size]; //initially stack is empty top = -1; } //add value to stack bool push(int i) { if (isFull()) return false; else { top++; stack[top] = i; } } int pop() { if (isEmpty()) throw new exception("Stack is empty"); else { return stack[top--]; } } //hidden data members and member functions private: //return true if stack is full bool isFull() { return size == top - 1; } bool isEmpty() { return top == -1; } int size; int* stack; int top; };
As you can see, myStack class provides only possibility to pop and push values and set size of stack. You don’t know how the value is inserted and returned. You are using this class for the main purpose of using Stack operation:
myStack s(5); for (int i = 0; i != 5; ++i) { cout << "pushing " << i << endl; //add values to stack s.push(i); } cout << "popping from stack" << endl; for (int i = 0; i != 5; ++i) { cout << s.pop() << endl; }