Edouardb Edouardb - 1 year ago 47
C++ Question

Inexplicable value of int variable in C++ class

I have been stuck with a problem in C++ for several hours now, and I can't figure out what's going on, even with the help of the debugger.

I am trying to create a

class which (no kidding) represents a date, with day, month and year. I also want to overload the main operator (++, --, +=, -=, +).

For a reason I cannot see, everything seems working fine, except the operator '+'.

Here is my header file:

#include <ostream>

class Date {
Date(int year, int month, int day);
Date(const Date& date);
Date &operator+(int days);

int m_year;
int m_month;
int m_day;
friend std::ostream &operator<<(std::ostream &os, const Date &date);

Here is my C++ file:

#include "Date.h"

using namespace std;

Date::Date(int year, int month, int day)
: m_year(year),

Date::~Date() {}

Date::Date(const Date &date)
: m_year(date.m_year),

ostream &operator<<(ostream &os, const Date &date) {
os << date.m_day << ", " << date.m_month << " " << date.m_year;
return os; <---- debug point A

Date &Date::operator+(int days) {
Date newDate(*this);
newDate.m_day = newDate.m_day + days;
return newDate; <---- debug point B

And my main file:

#include "Date.h"
#include <ostream>

using namespace std;

int main(int argc, char *argv[])
Date date(2013, 12, 12);
cout << date << endl;
cout << date + 2 << endl;
return 0;

And the output is:

12, 12 2013
1359440472, 12 2013

Process finished with exit code 0

I don't understand where does this 1359440472 comes from!!

I have tried to put debug point (as shown above), and the output is the following:

Debug point A:
date = {const Date &}
m_year = {int} 2013
m_month = {int} 12
m_day = {int} 12

Debug point B:
this = {Date * | 0x7fff5c5ddac0} 0x00007fff5c5ddac0
m_year = {int} 2013
m_month = {int} 12
m_day = {int} 12
days = {int} 2
newDate = {Date}
m_year = {int} 2013
m_month = {int} 12
m_day = {int} 14

Debug point A:
date = {const Date &}
m_year = {int} 2013
m_month = {int} 12
m_day = {int} 1549654616

I cannot explain that!! There is no step between the two last debug checkpoints, and "14" has become "1549654616"...

It could be a problem with the type
(as it seems to be not far from 2^24) or a problem with the operator +, but I don't see how to fix it.

Thanks you for your help,

Answer Source

You're returning a dangling reference.

Anything can happen.

Make your operator+ return by value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download