data abstraction in c++

Object Oriented Programming has a special feature called data abstraction. Data abstraction allows ignoring the details of how a data type is represented. While defining a class, both member data and member functions are described. However while using an object (that is an instance of a class) the built in data types and the members in the class are ignored. This is known as data abstraction. This can be seen from the above example.


Benefits of Data Abstraction

– Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.
– The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code.

By defining data members only in the private section of the class, the class author is free to make changes in the data. If the implementation changes, only the class code needs to be examined to see what affect the change may have. If data are public, then any function that directly accesses the data members of the old representation might be broken.

Example
#include <iostream.h>
#include <conio.h>

class base{
private: int s1,s2;

public: void inp_val()
{
cout <<“input the values of s1 and s2 “;
cin>>sl>>s2;
}

void display()
{
cout <<s1 <<” “<<s2<<“\n “;
}
};

void main(){
base b;
b.inp_val();
b.display();


Above class takes numbers from user, and returns both. The public members inp_val and display are the interfaces to the outside world and a user needs to know them to use the class. The private members s1 & s2 are something that the user doesn’t need to know about, but is needed for the class to operate properly.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s