Working of Objects as function arguments in C++ programming

Like any other data type, an object may be passed as function argument. It can be done in two ways
  1. a copy of entire object is passed to function.
  2. only the address of the object passed to the function.
class time
{
         private: int hours ,minutes;
         public:
         void sum (time, time); //function declaration taking argument of
 }; class type
void sum (time t1, time t2)
{ }

let us an example:

#include<iostream.h> 
class time
{
         int hour;
        int minutes;
        public: time() { }
        time(int h, int m)
       {
             hour=h;
             minutes=m;
        }
        void display()
       { 
                 cout<< hours<< “hours”;
                 cout<<minutes<<“minutes”<<"\n";
        }
        void sum(time, time);
};

void time:: sum(time t1,time t2)
{
        minutes= t1.minutes+t2.minutes;
        hour= minutes/60;
        minutes =minutes%60;
        hour= hour + t1.hour + t2.hour;
}
void main()
{
        time t1(2,40);
        time t2(3,35);
        time t3;
        t3.sum(t1,t2);
        t1.display();
        t2.display();
        t3.display();
}

Sample Output:


Post a Comment

Previous Post Next Post