Click here to Skip to main content
15,917,481 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Where should one put an enum, inside class definition/declaration or outside of it?

To an extent it's a matter of personal preference, but my general rule is "If it's class related, put it in the class"

There are reasons for putting in within the class:
1) It reduces the "Pollution" of the namespace by organising the structures in a hierarchical manner.
2) It groups related items together.
3) It lets you control the scope of classes which can use the enum - if they can't access the functions or data which refer to it, then they have no "need to know" of it's existence.

Others will tell you it means more typing when you use it: yes it does. And that can reduce readability to an extent. But I think that it's a good thing, because it ensures that you are using exactly the class / enum you think you are, not a similarly named one from a different source.
Share this answer
Dan page 16-May-13 4:00am    
what is the drawback of putting it outside the class?
OriginalGriff 16-May-13 4:13am    
The reverse of the advantages above! :laugh:
1) You get loads and loads of names within the namespace, which makes it harder to work out what is related to what, and how they work together.
2) See 1)
3) You can't hide enums from classes that don't need to see them - the availability is global (within the namespace)

well it depends on how the enum is used. If it is used only throughout one class, I would put it into that class. Otherwise the enum shall be nested in a different scoped (e.g. namespace, header file) so that is can be used by multiple classes/functions.

Hope this helps.

Best regards,
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900