Monday, September 5, 2011

Member Functions defined outside the class in C++ program


In our previous examples we have defined all functions within the class body. C++ program allows defining functions outside the body of classes also. In such case we have to declare the functions within the class body.

Here is a C++ program to demonstratethe above feature.

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

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner