Search code examples
c++classenumsdefinitionscoping

Define enum in class or in File?


Say that in file foo.h I have:

enum bar {
    ONE = 1,
    TWO
};

class foo {
    bar m_bar;
public:
    void setBar(bar arg){ m_bar = arg; }
    bar getBar() const { return m_bar; }
};

In my current design, the only persistent bar variable will be m_bar. But I will have other functions, outside of foo that contain a bar, for example a GUI class that creates a local bar and passes it to setBar.

So here's my question, is there any rationale to defining bar publicly inside foo versus just inside the class where it is?


Solution

  • So here's my question, is there any rationale to defining bar inside foo versus just inside the class where it is?

    If all the functions that create/work with bar are related to foo functionality, then it is perfectly acceptable to write it like this:

    class foo
    {
        enum bar {
            ONE = 1,
            TWO
        };
    };
    
    void process_bar_of_foo(foo::bar bar_value); // process the bar of a foo
    

    If on the other hand you can write code that has (conceptually) nothing to do with a foo instance but deals with bar values, you should probably write it separately.