Reputation: 59
This is a fairly basic problem but I'd like some input on what the best practice is. My issue is how do you propagate an enum from a sub-class to a higher level class so that it is visible to the main class's caller?
For example, say I have a class Bike. Bike will initialize sub-classes Wheel, Frame, Chain, etc. that make up a bike. Frame might have an enum such as FrameColor, Chain might have an enum such as LinkType, etc. Now let's say some higher level code wants to construct a Bike class. The constructor of Bike would require the caller to specify the LinkType, FrameColor, etc. I'd like to avoid putting the enum definitions inside a global header file, since this is bad C++ style.
Two possible approaches I've thought of but there must be a simpler, cleaner way:
Use an abstract class defining an interface
Forward declare the enum
Upvotes: 2
Views: 158
Reputation: 304122
Why do you need to propagate anything? As like as your subobjects have their enumerations clear, you can just use them directly. Once you have Frame::Color
, you don't need to make a Bike::Frame::Color
... the one is sufficient. For example:
struct Frame {
enum class Color {
BLACK, RED
};
Color c;
};
struct Bike {
Bike(Frame::Color c /*, Chain::LinkType lt, ..., */)
: frame{c}
{ }
Frame frame;
};
int main() {
Bike b{Frame::Color::RED};
}
Now, if Frame
is nested inside of Bike
, you can just alias the enum:
struct Bike {
struct Frame {
enum class Color { ... };
};
using FrameColor = Frame::Color;
};
Bike b{Bike::FrameColor::RED};
Upvotes: 4