0

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?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 1
    it's advisable to put the enum in an enclosing namespace if that enum is very specific to one concept or even a single class – BeyelerStudios Dec 14 '15 at 13:56
  • @BeyelerStudios So you're saying wrap foo.h in a namespace that encapsulates both the `enum` and the `class` but leave the `enum` out of the `class`? – Jonathan Mee Dec 14 '15 at 13:58
  • you can apply the same considerations to your class `foo` - if that fits your design - if you prefer to use general nomenclature (i.e. `Sample`) for your classes maybe a namespace for them would be appropriate as well... – BeyelerStudios Dec 14 '15 at 14:01

2 Answers2

2

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.

utnapistim
  • 26,809
  • 3
  • 46
  • 82
0

Well, as it stands, you can create bar objects with objects and functions outside of the foo class like you mentioned and then pass it to whatever foo object you make.

If you were to, however, define it in the class, then you wouldn't really be able to make bar objects unless you create a foo class first which can lead to unnecessary overhead if you just want to enum object.

And so it really depends on what you're going to do. If you only plan on using bar with the foo class, then it would be perfectly acceptable to define it there. Otherwise if it's going to be accessed elsewhere, leave it as is.

Amposter
  • 787
  • 2
  • 8
  • 27