Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.
Let's take one real life example of a TV which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players BUT you do not know it's internal detail that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen.
Thus we can say, a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having zero knowledge of its internals.
In C++ we use classes to define our own abstract data types (ADT). You can use the cout object of class ostream to stream data to standard output like this:
#include <iostream> using namespace std; int main( ) { cout << "Hello C++" <<endl; return 0; }
Here you don't need to understand how cout displays the text on the user's screen. You need only know the public interface and the underlying implementation of cout is free to change.
Data Abstraction Example:
Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following example:
#include <iostream> using namespace std; class Adder{ public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main( ) { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0; }
When the above code is compiled and executed, it produces following result:
Total 60
Above class adds numbers together, and returns the sum. The public members addNum and getTotalare the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that the user doesn't need to know about, but is needed for the class to operate properly.