Thomas Martin
Thomas Martin

Reputation: 112

Getting stack overflow when overloaded >> operator function is called for a class. What changes do i need to make?

Below is the class file for which >> operator is overloaded.

class Timepoint {
public:
    Timepoint();
    Timepoint(unsigned short yearValue = 9999, unsigned short month = 12, unsigned short date = 31, unsigned short hour = 23, unsigned short minute = 59);
    ~Timepoint();
    unsigned short get_dayOfYear();
    void operator++();
    friend std::ostream& operator<<(std::ostream& out, const Timepoint& timepoint);
    friend std::istream& operator>>(std::istream&, const Timepoint&);

private:
    unsigned short dayOfYear;
    unsigned short year;
    unsigned short time;
    const static short days[];
};

Below is the overloaded function which is triggering the stack overflow error. I have to take time as a time stamp from user and store in objects data. when control comes to this function, stack overflow is triggered.

std::istream& operator>>(std::istream& in, const Timepoint& timepoint)
{
    int day, month, hour, minute;
    std::string timestamp;
    in >> timestamp;
    std::stringstream ss(timestamp);
    ss >> timepoint.year;
    ss.ignore();
    ss >> month;
    ss.ignore();
    ss >> day;
    ss.ignore();
    ss >> hour;
    ss.ignore();
    ss >> minute;

    const_cast<Timepoint&>(timepoint).dayOfYear = timepoint.days[month] + day;
    const_cast<Timepoint&>(timepoint).time = hour * 60 + minute;
    return in;
}

Upvotes: 1

Views: 83

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52611

ss >> timepoint.year is interpreted as

ss >> Timepoint(timepoint.year);

That's the only viable way to read into a const unsigned short. This of course results in an infinite recursion.

The root cause here is that you are, inexplicably, passing a const object to a function whose explicit goal is to modify that object. Just drop const.

You may also want to make the constructor explicit, to avoid such unexpected conversions.

Upvotes: 2

Related Questions