Hello Guys,

I am trying to implement a coparison operator == into a try catch block to compare to clocks. I defined my comparator as

friend bool operator ==(Clock&c1,Clock&c2)
    {
        return(c1.get_hour()==c2.get_hour() && c1.get_minute()==c2.get_minute());
    }

and my try catch block as

 Clock *clock3;
try{
    int hour,minute;
    cout<<"Hour: ";
    cin>>hour;
    cout<<"Minute: ";
    cin>>minute;
    cout<<endl;
    clock3= new Clock(hour,minute);
   if(&clock2==clock3) // Clock clock2(8,30);
    {throw 'a';}
}
catch(char a)
{
    cout<<"same time"<<endl;
}

For some reason it is unable to compare clock2 and clock3. Any suggestions? :) Thanks a lot!

Your comparison operator takes two references, but you call it with two pointers. When you have &clock2 == clock2, you are taking the address of clock2, which gives you a pointer Clock*, and then, you compare it to clock3, which is already a pointer. What you need to do is clock2 == *clock3, which dereferences clock3 and calls the comparison operator with two objects (implicitely taken by reference in the comparison operator).

And by the way, the comparison operator does not modify the objects referred to by the references it is given. So, you should take those objects by const-reference instead (and make your "getter" member functions get_hour and get_minute const as well), as so:

friend bool operator ==(const Clock& c1, const Clock& c2)
{
    return(c1.get_hour()==c2.get_hour() && c1.get_minute()==c2.get_minute());
}

// with the getters declared 'const' like this:
int get_hour() const;
int get_minute() const;

Also, note that if you implement the comparison operator only in terms of public member functions of the Clock class, then you don't need to make it a friend function, you simply defining outside the Clock class as a normal non-friend function. Don't use friend more than you have to, as a general tip for good coding practices.

commented: Crystal clear sir! Thanks a lot! +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.