Game Development Reference
In-Depth Information
when we really meant to use the Color version. The compiler would assume that we meant Blue as
both Color::Blue and TrafficLights::Green are representations of 2. Using an enum class, however,
means the code must look like this:
Color currentColor = Color::Red;
TrafficLights = currentLight = TrafficLights::Red;
As you can see, the strongly typed version of enums is much better and provides us with more
explicit code. Always use an enum class where possible in new code.
Enums are the last type introduced in this chapter. We can now spend the rest of the chapter looking
at the different types of operators that C++ supplies to work with our types.
Switching from One Type to Another
Sometimes while writing our programs we will have a value stored as one type, such as an int ,
but we would like to use the value from our variable along with a value stored in another variable.
Fortunately C++ can automatically convert from some types to others. The following lines of code
provide some examples:
char charNumber = 1;
int intNumber = charNumber;
float floatNumber = intNumber;
C++ can implicitly convert numbers from one type to another. Going from smaller types to larger
types and from integer types to floats and floats to doubles as well as from integer types to bools are
all legal and carried out automatically by the compiler.
static_cast
Whereas moving from a smaller type to a larger type is safe, moving from a larger type to a smaller
type can cause a loss of data. For example:
int largeNumber = 1000;
char smallNumber = largeNumber;
In this case, the large number would likely be truncated from 1,000 to 127, as that is the largest
number that a signed char variable can hold. This type of data loss is known as a narrowing
conversion. C++ compilers give warnings about this type of conversion and many game
development studios like to keep their code error-free or enable compiler settings that cause all
warnings to become errors. Fortunately C++ provides us with a method to tell the compiler that we
were converting this value on purpose. This method is known as a static cast. An example of the
usage of static _ cast would be:
char smallNumber = static_cast<char>(largeNumber);
This code tells the compiler that we are purposefully converting our type to a char and it will not
output any warnings for the conversion.
 
Search WWH ::




Custom Search