Search code examples
c++constructorenumsfltk

Enumerator instead of constructor for class instantiation?


I have a struct Color with an enumeration Color_type. The constructor has an argument of type Color_type; Fl_Color, FL_REDand FL_BLUE are a class and constants from FLTK:

struct Color {
    enum Color_type {
        red = FL_RED,
        blue = FL_BLUE,
        // et cetera
    };

    Color(Color_type cc) :c(Fl_Color(cc)) { }
private:
    Fl_Color c;
};

Another type has a member function to set the color, like this:

class Grid {
    void set_color(Color col) { lcolor = col; }
private:
    Color lcolor;
};

I would expect this function to be called like this:

my_grid.set_color(Color(Color::red));

i.e., call the constructor with the enumerator, like declared. However, it also works like this:

my_object.set_color(Color::red);

Why? Is this a legal shorthand?


Solution

  • Your constructor allows implicit conversions from Color_type to Color. If you don't want to allow that, you need to make it explicit:

    explicit Color(Color_type cc) :c(Fl_Color(cc)) { }