Saturday 17 September 2011

Pointer to data member


Pointer to data member
Aim:
To write a C++ program to find the area of rectangle using pointer to data member.
Algorithm:
Step 1: Create a class as rectangle.
Step 2: Declare the data members a, b, *x,*y.
Step 3: Declare the member functions as getdata() and area().
3.1 In the getdata() function, get the length and breadth of the rectangle and store their address to the pointer variable.
3.2 In the area() function, display the area of the rectangle.
Step 4: In the main, create an object for the rectangle class using the following syntax:
Classname objectname;
Step 5: Call the getdata() and area() function using the following syntax:
Objectname.methodname();
Program:
#include<iostream.h>
#include<conio.h>
class rectangle
{
 int a,b,*x,*y;
 public:
 void getdata();
 void area();
};
void rectangle :: getdata()
 {
  cout<<"Enter the length of the rectangle:";
  cin>>a;
  cout<<"Enter the breadth of the rectangle:";
  cin>>b;
  x=&a;
  y=&b;
 }

 void rectangle :: area()
  {
   cout<<"The area of the rectangle is:"<<*x**y;
  }

  void main()
   {
    rectangle r;
    clrscr();
    r.getdata();
    r.area();
    getch();
   }

Output:

Enter the length of the rectangle:12
Enter the breadth of the rectangle:15
The area of the rectangle is:180

0 comments:

Post a Comment