Home > Software design >  Why does this overloaded operator<< work in an unexpected way?
Why does this overloaded operator<< work in an unexpected way?

Time:02-01

I want to create a method to add color to console output. I have an idea in my head similar to std::left and std::setw(). I ended up with the code below, and it works exactly how I want it to.

I understand how it works, but I would like some clarifications on some things to better my knowledge.

Here is the code:

#include <iostream>
#include <Windows.h>

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

enum class color { blue = FOREGROUND_BLUE, green, cyan, red, purple, yellow, white, bright = FOREGROUND_INTENSITY };

class coutColor {
public:

    WORD Color;

    coutColor(color colorvalue) : Color((WORD)colorvalue) {  }
    ~coutColor() { SetConsoleTextAttribute(hConsole, (WORD)7); }

};

std::ostream& operator<<(std::ostream& os, const coutColor& colorout) {

    SetConsoleTextAttribute(hConsole, colorout.Color);
    return os;

}

int main() {

    std::cout << coutColor(color::green) << "This text is green!\n";
    std::cout << color::red << "This text is red! " << 31 << "\n";

    return 0;
}

I understand how coutColor(color::green) works in the cout in main(), but why does just color::red by itself work as well?

I stumbled upon it by accident while testing different things.

How can it take the enum type color as an input, since it's not in the input parameters of the overloaded operator<<?

Why does it do the same thing as inputting coutColor(color::red)?

CodePudding user response:

why does just color::red by itself work as well? ... How can it take the enum type color as an input, since it's not in the input parameters of the overloaded operator<<? Why does it do the same thing as inputting coutColor(color::red)?

It is because coutColor's constructor is not marked as explicit.

When the compiler is looking for a suitable overload of operator<< for the expression std::cout << color::red, it finds your overload in scope and sees that:

  1. coutColor is implicitly constructable from a color value

  2. the operator takes a coutColor object by const reference

So, the compiler is able to create a temporary coutColor object, passing the color value to its constructor, and then pass that object to the operator.

I have seen function(input) : var(input) {} before and I didn't know what it meant.

C , What does the colon after a constructor mean?

  •  Tags:  
  • c
  • Related