I wrote a simple program to demonstrate the use of overloaded operator << in c++. According to this article: https://docs.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes?view=msvc-160, I tried writing my own code:
#include <iostream>
#include <string>
class Date
{
private:
std::string str;
public:
Date(int x) : str(5, 'x'){}
friend std::ostream& operator<<(std::ostream& os, const Date& dt){
os << dt.str;
return os;
}
};
int main()
{
Date dt(6);
std::cout << dt;
}
This code worked correctly as it printed "xxxxx" to the console. However when I remove the argument of the constructor:
#include <iostream>
#include <string>
class Date
{
private:
std::string str;
public:
Date() : str(5, 'x'){}
friend std::ostream& operator<<(std::ostream& os, const Date& dt){
os << dt.str;
return os;
}
};
int main()
{
Date dt();
std::cout << dt;
}
, I got "1" printed to the console. I have no idea why this happens.