Tuesday, December 9, 2014

Functions and object pro in c++



Friend Function


#include
#include
class sample
{
   int a,b;
   public :
     void setvlaue()
    {
       a = 25; b = 20;
     }
 friend float mean (sample s);
 };
float mean (sample s)
 {
  return float (s.a+s.b)/2.0;
 }
int main ()
{
  sample x;
  x.setvalue();
  cout << " Mean Value is =" << mean(x) <<"\n";
}

Objects as Function Arguments


#include
#include
class time
{
   int hours, minutes;
   public : 
   void gettime(int h, int m)
  {
  hours=h; minutes=m;
  }
  void puttime()
 {
  cout << "hours"<< hours;
  cout << "time" << time;
  }
  void sum(time,time);  
  };  
 void time :: sum(time t1,time t2)
{
  minutes = t1.minutes + t2.minutes;
  hours = minutes /60;   minutes = minutes%60;
  hours = hours + t1.hours +t2.hours;
 }
int main()
{
   time t1,t2,t3;
   t1.gettime(2,45);
   t2.gettime(3,30);
   t3.sum(t1,t2);
   cout << "t1 ="; t1.puttime();
   cout << " t2 = "; t2.puttime();
   cout << "t3 = " ; t3.puttime();
 }  

Code for Program that provides an example of function returning object in C++ Programming

# include 
# include 
class data
{
    int a,b;
    public:
        void get();
        friend data sum (data,data);
        void show();
};
data sum(data a1,data a2)
{
    data a3;
    a3.a=a1.a+a2.a;
    a3.b=a1.b+a2.b;
    return a3;
}
int main()
{
    clrscr();
    data a,b,c;
    a.get();
    b.get();
    c=sum(a,b);
    c.show();
}
void data::get()
{
    cout<<"Please enter for a:->";
    cin>>a;
    cout<<"Please enter for b:->";
    cin>>b;
}
void data::show()
{
    cout<<"A= "<
    cout<<"B= "<
}

1 comment:

  1. Write C++ program to implement calculate_Temperature function as friend function to Temperature class by using following functions as member methods in Temperature class.
    1- Constructor().
    2- setVlaue().
    3- getValue().
    4- calculate_Temperature (Friend Function) to convert temperature from Fahrenheit to Celsius.
    5- Display().

    ReplyDelete