-1

topic -- reference variable

In c++

This is a program that tells the user what the time is using opps and classes(time class). It runs as I expect it , when I do not pass the time(t) as a reference it throws a garbage value(or whatever the problem is if you want to be more specific) when I pass it as reference variable it works perfectly. I am struggling to understand that why we need to pass reference of time class. Any explanation would be appreciated.

source code---

#include <iostream>
using namespace std;

class time{

    int hh=0,mm=0,ss=0;

public:
  friend  void operator>>(istream &in,time &t);

  friend void operator<<(ostream &out,time &t);

  friend void operator==(time,time);

};

   void operator>>(istream &in,time &t){
   
       
          cout<<"enter hours:";in>>t.hh;cout<<endl;
          cout<<"enter minutes:";in>>t.mm;cout<<endl;
          cout<<"enter seconds:";in>>t.ss;cout<<endl;

    }


   void operator<<(ostream &out,time &t){

       out<<"hours :"<<t.hh;out<<endl;
       out<<"minutes :"<<t.mm;out<<endl;
       out<<"seconds :"<<t.ss;out<<endl;

   }

 
 void operator==(time t1,time t2){

    if (t1.hh == t2.hh && t1.mm == t2.mm && t1.ss == t2.ss)
    {
        cout<<"same time";
    }
    else
        cout<<"different time";
    
 }

int main(){
  time t1,t2;

  cin>>t1;
  cout<<t1;

  cin>>t2;
  cout<<t2;

  t1 == t2;

 return 0;
}

I am struggling to understand that why we need to pass reference of time class. Any explanation would be appreciated.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • `void operator<<(ostream &out,time &t){` is screwed anyways. Take a look at [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading?r=Saves_AllUserSaves) please! – πάντα ῥεῖ Nov 25 '22 at 13:25
  • If you used `void operator>>(istream &in,time t)` what object do you think you were writing to? You did explicitly take a copy – UnholySheep Nov 25 '22 at 13:26
  • You mean why pass by reference to `operator>>(istream &in,time &t)`? Because you modify `t`. But all this code is in principle broken, starting with `using namespace` followed by `class time`. – pptaszni Nov 25 '22 at 13:28

1 Answers1

0

The only place where you really need reference is where you'd like to modify the value. E.g. in operator>>, you need to be able to set it according to user input.

For optimization reasons, we tend to take const time& instead of time when the object is non-minimal (i.e., not just an int/long/etc.).

However, there are other issues in your code: operator<< and operator>> should return the in and out arguments, respectively (thus they shouldn't be void) as per common practice and you shouldn't have using namespace std; at namespace-level to avoid collision.

lorro
  • 10,687
  • 23
  • 36