CPP Program


/*Illustrate the use of dereferencing operators to access the class 
members through pointers.  To implement this, define a class M 
with x and y as data members.  Define two methods. One is to input 
the values of x and y and other to find the sum.  The sum is a friend 
function and object of class M is passed as argument in sum.  
Sum will access the class members through dereferencing operators.  
Implement the program and display the results in a neat format
*/

#include<iostream.h>
#include<conio.h>
class M
{
      int x,y;
   public:
      void getdata(void){cout<<"Enter X : ";cin>>x;
			 cout<<"Enter Y : ";cin>>y;}
      friend void sum(M);
};
void sum(M m)
{
   M *pm = &m;
   int M:: *px = &M::x;
   int M:: *py = &M::y;
   cout<<endl<<"The sum = "<<pm->*px+pm->*py;
}
void main()
{
   clrscr();
   M om;
   om.getdata();
   sum(om);
   getch();
}

Alternate 

#include<iostream.h>
#include<conio.h>
class M
{
      int x,y;
   public:
      void getdata(void){cout<<"Enter X : ";cin>>x;
			 cout<<"Enter Y : ";cin>>y;}
      friend void sum(M);
};
void sum(M m)
{
   int M:: *px = &M::x;
   int M:: *py = &M::y;
   cout<<endl<<"The sum = "<<m.*px+m.*py;
}
void main()
{
   clrscr();
   M om;
   om.getdata();
   sum(om);
   getch();
}

No comments:

Post a Comment