user3221454 user3221454 - 8 months ago 47
C++ Question

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

Here is an example taken from

#include <iostream>
using namespace std;

class Date
int mo, da, yr;
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.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


But what I get was


What or how can I work this out?

Answer Source

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;