Mo Sanei
Mo Sanei

Reputation: 475

Why does my code need <iostream>?

I wrote some basic code I learned that can be used to define a type that gets an enumerated value as its constructor argument and has a member function AsString() that returns the value as a string.

The code doesn't compile unless I include <iostream>. It displays a warning in main saying that the type color has not been declared. Why is it required to include an input/output header file in my code while no input/output functions or operators are used in it?

enum ColorEnum {blue, red};

class color
{
    protected:
        ColorEnum value;
    public:
        color(ColorEnum initvalue)
        {
            value = initvalue;
        }
        std::string AsString()
        {
            switch (value)
            {
                case blue:
                    return "blue";
                case red:
                    return "red";
                default:
                    return "N/A";
            }
        }
};

int main()
{
    color mycolor = blue;
    return 0;
}

Upvotes: 0

Views: 507

Answers (2)

juanchopanza
juanchopanza

Reputation: 227608

You do not need <iostream>, you need <string> for std::string, which you may be getting indirectly via <iostream>.

Upvotes: 7

Luchian Grigore
Luchian Grigore

Reputation: 258678

You don't need to include <iostream>, but <string>, because you use std::string, so that might set the compiler off.

If you include <string> and still get the error, that sounds like a bug in the compiler.

Upvotes: 5

Related Questions