summaryrefslogtreecommitdiffhomepage
path: root/c++.html.markdown
diff options
context:
space:
mode:
authorCameron Wood <github@cbwood.net>2015-10-17 06:05:54 -0400
committerCameron Wood <github@cbwood.net>2015-10-17 06:05:54 -0400
commitca435fbb0dd09cdc9c70fe945a891ae3e6c19ab2 (patch)
treec6352c6abde82cfd0b1b717eaede8aaa350817df /c++.html.markdown
parent0e6d9f6fe9aeffc64c3adad3e4a0ee1cc0d1dd88 (diff)
[C++/en] Added in Enum information
Added in some information about enums in C++ including some different use cases
Diffstat (limited to 'c++.html.markdown')
-rw-r--r--c++.html.markdown64
1 files changed, 64 insertions, 0 deletions
diff --git a/c++.html.markdown b/c++.html.markdown
index 2bee51dc..d03092e5 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -310,6 +310,70 @@ basic_string(basic_string&& other);
// constructor that "salvages" parts of that temporary string. You will see this
// concept referred to as "move semantics".
+/////////////////////
+// Enums
+/////////////////////
+
+// Enums are a way to assign a value to a constant most commonly used for
+// easier visualization and reading of code
+enum ECarTypes
+{
+ Sedan,
+ Hatchback,
+ SUV,
+ Wagon
+};
+
+ECarTypes GetPreferredCarType()
+{
+ return ECarTypes::Hatchback;
+}
+
+// As of C++11 there is an easy way to assign a type to the enum which can be
+// useful in serialization of data and converting enums back-and-forth between
+// the desired type and their respective constants
+enum ECarTypes : uint8_t
+{
+ Sedan, // 0
+ Hatchback, // 1
+ SUV = 254, // 254
+ Hybrid // 255
+};
+
+void WriteByteToFile(uint8_t InputValue)
+{
+ // Serialize the InputValue to a file
+}
+
+void WritePreferredCarTypeToFile(ECarTypes InputCarType)
+{
+ // The enum is implicitly converted to a uint8_t due to its declared enum type
+ WriteByteToFile(InputCarType);
+}
+
+// On the other hand you may not want enums to be accidentally cast to an integer
+// type or to other enums so it is instead possible to create an enum class which
+// won't be implicitly converted
+enum class ECarTypes : uint8_t
+{
+ Sedan, // 0
+ Hatchback, // 1
+ SUV = 254, // 254
+ Hybrid // 255
+};
+
+void WriteByteToFile(uint8_t InputValue)
+{
+ // Serialize the InputValue to a file
+}
+
+void WritePreferredCarTypeToFile(ECarTypes InputCarType)
+{
+ // Won't compile even though ECarTypes is a uint8_t due to the enum
+ // being declared as an "enum class"!
+ WriteByteToFile(InputCarType);
+}
+
//////////////////////////////////////////
// Classes and object-oriented programming
//////////////////////////////////////////