user3221454 user3221454 - 12 days ago 6
C++ Question

c++ overload ostream doesn't work for default construct with empty argument

Here is an example taken from https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

#include <iostream>
using namespace std;

class Date
{
int mo, da, yr;
public:
Date()
{
mo = 10; da = 10; yr = 99;
}
Date(int m, int d, int y)
{
mo = m; da = d; yr = y;
}
friend ostream& operator<<(ostream& os, const Date& dt);
};

ostream& operator<<(ostream& os, const Date& dt)
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}

int main()
{
Date dt0();
cout << dt0 << endl;

Date dt(5, 6, 92);
cout << dt;
}


I'd expect the output to be

10/10/99
5/6/92


But what I get was

1
5/6/92


What or how can I work this out?

Answer

Welcome to C++, where you can get tripped up because of the most vexing parse!

dt0 is not an object, it is a function! When you output it, you are actually outputting the address of the function dt0, which always evaluates to true, i.e. 1.

You can replace the () with {}, so not ambiguity occurs:

Date dt0{};

Or just drop the parenthesis altogether:

Date dt0;