unexpected behavior of overloaded operator “<<” c++

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.

Answer

Try with following:

    int main()
    {
        Date dt;
        std::cout << dt;
    }

Which compiler you are using? Microsoft C++ compiler report a linking error with your main function without arg i.e. Date dt();

error LNK2001: unresolved external symbol "class Date __cdecl dt(void)" ([email protected]@[email protected]@XZ)

Leave a Reply

Your email address will not be published. Required fields are marked *