Segmentation fault when I'm trying to overload operator<< for char

63 Views Asked by At

When I'm trying to overload operator<< for char and use it which std::cout something is wrong.During compilation I don't have any errors but when i type ./a.outi see Segmentation fault (core dumped).

This is code:

#include <iostream>

std::ostream & operator<<(std::ostream & COUT, char letter)
{
    COUT << letter;
    return COUT;
}

int main(void)
{
    std::cout << 'l';
}

Thanks for every help.

1

There are 1 best solutions below

0
Some programmer dude On

The problem is that the statement

COUT << letter;

will invoke your own overloaded function, leading to infinite recursion.

You need to explicitly call the "normal" overloaded function:

std::operator<<(COUT, letter);

On a different note, because the << operator returns a reference to the stream, you can use it in your own function as a single statement:

return std::operator<<(COUT, letter);

For characters and strings, it's a nonmember function, for everything else it's a member function. So for example int you need to call the member function instead:

std::ostream& operator<<(std::ostream& out, int value)
{
    return out.operator<<(value);
}