Saturday, September 3, 2011

Encapsulation in C++ programs


In my last post, encapsulation is discussed. Encapsulationis very much important for cbse students. In most of the cbse C++ sample paper, you will find at least 2-3 programs purely based on encapsulation. Here is a program demonstrating encapsulation in C++.


#include< iostream.h >
#include< conio.h >
class Rect
{
private:
int len, br;
public:
void getData ()
{
cout<< endl<< "Enter Length and Breadth: -";
cin>>len>>br;
}
void setData (int l, int b)
{
len=l;
br=b;
}
void displayData ()
{
cout<< endl<< "Length="<< len;
cout<< endl<< "Breadth="<< br;
}
void area ()
{
int a, p;
a=len*br;
p=2*(len+br);
cout<< endl<< "Area="<< a;
cout<< endl<< "Perimeter="<< p;
}
};
void main ()
{
clrscr ();
Rect r1, r2, r3;
cout<< endl<< "For object number 1: -";
r1.setData (10,20);
r1.displayData ();
r1.area ();
cout<< endl<< "For object number 2: -";
r2.setData (3,5);
r2.displayData ();
r2.area ();
cout<< endl<< "For object number 3: -";
r3.getData ();
r3.displayData ();
r3.area ();
getch ();
}

The class Rect specified in the above C++ program contains two data members’ len and br and four function members getData (), setData (), displayData () and area (). The first function getData (int, int) takes two integer values from the user and set them in the two data members of the object of Rect class. setData () function sets constant values in the data items of the object. displayData () function displays the values of the data members of an object of class Rect while area () function calculates and displays the area and perimeter.

The body of the class Rect contains two unfamiliar keywords private and public. They are used in C++ programs to implement a concept known as data hiding, encapsulation in C++.  private data and function members can be accessed from within the class where public members are accessible from outside the class. The function members provide controlled access to the data members of an object. Usually the data members within a class are private and the function members are public. When the class is created let’s have a look how main () function makes use of it.

Rect r1, r2, r3; defines three objects r1, r2 and r3 of class Rect. Remember that the specifications of the class does not create any object, it only describes how the objects will look when they are created. It is the definition that actually creates objects, which can be used by the program. Thus, defining an object is similar to defining a variable of any data type- space is set-aside for it in memory.

Next is r1.setData (10, 20); this statement does not look like a normal function call. The name of the object r1 is associated to the function using a dot (.). This syntax is used to call a function member that is associated with a specific object.

1 comment:

Subscribe via email

Enter your email address:

Delivered by FeedBurner