Gautam Nath Gautam Nath -4 years ago 152
C++ Question

C++ comparing variables as an object

I'm trying to compare two variables and the type of these variables are "Time". I can't seem to use the == / != function for these.

#include "Stock.h"

using namespace std;

void Stock::setShares(int d, int m, int y, int h, int mts, double p, int vol, double val)
date.setDate(d, m, y);
time.setTime(h, mts);
price = p;
value = val;
volume = vol;

Date Stock::getDate() const
return date;

Time Stock::getTime() const
return time;

This is in my main program:

Time t1, t2;
for (int i = 1; i < counter; ++i)
if ( == highestPrice)
time2 =;
if (time2 != time1)
cout << time2;

How can I compare time1 & time2? I'm trying to avoid printing duplicate values of time in my program. V1 is a vector loaded with data from Stock object.

Answer Source

Check first whether == or != operator is overloaded for type Time. You must provide your own meaning to operators which you are gonna to use in your code for user-defined types else you will get compiler errors.

something like below,

class Time
      bool operator==(Time const & t1) const
         return this.hour == t1.hour && this.min==t1.min;

     int min;
     int hour;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download