user1887990
user1887990

Reputation: 101

istream operator overloading c++

i'm trying to do a simple istream operator overloading, but for some reason, once entering this function, the program enters an infinite loop. please help!

my code:

#include <iostream>
#include <string>
using namespace std;

 class date{

int m_day,m_month,m_year;

public:

date(int day=1,int month=1,int year=2000){    //constructor
    if (day>0 && day<32 && month>0 && month<13){
        m_day =day;
        m_month=month;
        m_year=year;
    }
}


friend ostream& operator<< (ostream& out, const date& d);
friend istream& operator>> (istream& in, const date& d);
};


istream& operator>> (istream& stream, const date& d){              //overload >>
stream >> d.m_day;
return stream;

}

void main(){  

date date1;

cin>>date1;                   //check istream

getchar();
}

Upvotes: 2

Views: 21263

Answers (2)

tarcisioe
tarcisioe

Reputation: 21

Actually the answer by Marc does not solve your problem completely. What is happenning is a bit more complicated:

You defined the function receiving a const &. That should have made the compiler simply refuse to compile your function. But here lies the problem: your constructor for date has default values for every parameter. Therefore, it can be called with only one parameter. Since it is not marked explicit, it works as an implicit conversion operator for an int (like date(i)). This means the compiler can interpret stream >> d.m_day as stream >> date(d.m_day). Your problem thus was: this is a call for operator>>(istream& stream, const date& d) and you get an infinite recursion.

Thus, you should not only make date& d non-const on your overload of operator>>, you should also mark the constructor explicit, like

explicit date(int day=1, int month=1, int year=2000)

so that it doesn't act as an implicit conversion operator. This should be done, actually, to almost every constructor that can possibly take only one parameter.

Upvotes: 2

Marc Claesen
Marc Claesen

Reputation: 17036

This code seems wrong to me, since you are trying to modify a const object (d).

istream& operator>> (istream& stream, const date& d){              //overload >>
    stream >> d.m_day;
    return stream;    
}

Upvotes: 8

Related Questions