< C++ .NET Value Type 3 | Main | C++ .NET Operator Overloading 1 >


 

 

Value Types 4

 

 

What we have in this page?

 

  1. Enumerations

  2. Creating and Using an Enum

  3. Using Enums in Programs

  4. Another Example

  5. Avoiding Ambiguity

  6. Using Memory Efficiently

  7. Quick Reference

 

 

Enumerations

 

An enumeration (enum) is a set of named integer constants. Enums are especially suitable for representing types that can take one of a set of fixed values, such as the days of the week or the months of the year. Enums are value types, and they derive from the abstract System::Enum class, which in turn derives from System::ValueType.

 

Creating and Using an Enum

 

In the following exercise, you will create an enum to hold values representing the days of the week and then use it in a program.

 

1.        Start Visual C++/Studio .NET, and create a new CLR Console Application project named Enums.

 

Creating a new CLR Console Application project named Enums

 

2.        At the top of the Enums.cpp file immediately under the using namespace System; line, add the following structure definition:

// The Weekday enum definition

// old syntax: __value enum WeekDay

enum class WeekDay

{

    Monday, Tuesday, Wednesday, Thursday, Friday,

    Saturday, Sunday

};

The enum keywords start an enum definition, and you’ll notice that, once again, enums are defined similarly to classes. The body of the enum is enclosed in braces and finishes with a semicolon. This is a value type and not a traditional C++ enum. The enum itself consists of a comma-separated set of names, each of which represents an integer constant.

 

3.   Create enum variables the same as you create any other type. To create and initialize a WeekDay object, add the following lines to the main function of your application:

// Create a WeekDay

WeekDay w = WeekDay::Monday;

As with structs, the code doesn’t use the new operator. An enum named WeekDay has been created on the program stack, and you access it directly as w. Notice how the enum variable is initialized with one of the members of the enum. This syntax is how you initialize enum variables and how you can change their values later on.

 

4.        Try printing out the value of the WeekDay object like this:

Console::Write("Value of w is ");

Console::WriteLine(w);

The value 0 should be printed. Each of the named constants making up the enum represents an integer value. By default, these values start from 0 and increase by one for each subsequent member of the enum. You can test this output by changing the value you initially assign to w to be, for example, Saturday. When you run the code again, the value 5 should be printed. Even though the value given to an enum is an integer, there’s no implicit conversion between enums and integers. If you consider the following lines of code, you’ll understand why:

//** This code won’t compile! **//

// ’1’ would mean Tuesday

w = 1;

// What would ’8’ mean?

w = 8;

If converting between integers and enums were allowed, it would be possible to put invalid values into the enum. Going the other way is okay, though, because any enum value is a valid integer. You don’t have to rely on the default numeric values that are assigned to the enum members. Suppose you want the integer equivalents of the weekdays to range from 1 through 7 instead of 0 through 6; simply assign 1 to the Monday member, as shown here:

enum class WeekDay

{

    Monday = 1, Tuesday, Wednesday, Thursday, Friday,

    Saturday, Sunday

};

The enum will now start with 1, and because you haven’t given any other values for the remaining members, they’ll be numbered 2 through 7.

If you want, you can give a completely discontinuous series of values for the enum members, as in this example:

enum class StatusCodes

{

    OK=0, FileNotFound=2, AccessDenied=5, InvalidHandle=6, OutOfMemory=8

};

Using Enums in Programs

 

In this exercise, you’ll see how to use an enum to control program execution by using it in a switch statement.

 

1.  Use the same application as in the previous example. If you’ve closed it, select FileOpen Solution to open the project again. After the WriteLine statements, add the following switch statement code:

// Switch on the weekday

switch(w)

{

case WeekDay::Monday:

    Console::WriteLine("It’s a Monday!");

    break;

case WeekDay::Tuesday:

    Console::WriteLine("It’s a Tuesday!");

    break;

case WeekDay::Wednesday:

    Console::WriteLine("It’s a Wednesday!");

    break;

default:

    Console::WriteLine("It’s some other day...");

}

You are allowed to use an enum variable as a switch control variable because it’s basically an integer. Likewise, you can use the names of enum members as switch case labels because they’re also integers. The example code has cases for Monday through Wednesday; everything else is handled by the default case. Remember to put the break statements in after the code for each case, or the program won’t behave as you expect. A complete code with the output is shown below. Build and run this program.

 

// Enums.cpp : main project file.

#include "stdafx.h"

 

using namespace System;

 

// WeekDay variables are one byte in size

enum class WeekDay

{

    Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

};

 

int main(array<System::String ^> ^args)

{

      // Create a WeekDay

      WeekDay w = WeekDay::Monday;

 

      Console::Write("Value of w is ");

      Console::WriteLine(w);

      // Switch on the weekday

      switch(w)

      {

      case WeekDay::Monday:

            Console::WriteLine("It’s a Monday!");

            break;

      case WeekDay::Tuesday:

            Console::WriteLine("It’s a Tuesday!");

            break;

      case WeekDay::Wednesday:

            Console::WriteLine("It’s a Wednesday!");

            break;

      default:

            Console::WriteLine("It’s some other day...");

      }

    return 0;

}

 

Output:

Using enum in a program console output sample

 

Another Example

// Enums.cpp : main project file.

// A comparison of enum constructs, compile with: /clr

#include "stdafx.h"

using namespace System;

 

// managed enum

public enum class m { a, b };

 

// standard enum

public enum n { c, d };

 

// unnamed, standard enum

public enum { e, f } o;

 

int main() {

   // consume managed enum

   m mym = m::b;

 

   System::Console::WriteLine("No automatic conversion to int = {0}", mym);

   System::Console::WriteLine("Convert mym to int value = {0}", (int)mym);

   // consume standard enum

   n myn = d;

   System::Console::Write("myn = d = ");

   System::Console::WriteLine(myn);

   // consume standard, unnamed enum

   o = f;

   System::Console::Write("o = f = ");

   System::Console::WriteLine(o);

}

 

Output:

 

 

 

 

 

 

 

------------------------------------------------

A comparison of enum constructs program output sample

 

Avoiding Ambiguity

 

The names of enum members don’t have to be unique, but if they aren’t, you might need to qualify them with the name of the enum to which they belong to avoid ambiguity. Suppose that you have two enums declared in your program,  Direction and Mood, both of which have a Down member. Here’s how you’d have to use them:

int myMood = Down;          // ambiguous

int myMood = Mood::Down;    // OK

Using Memory Efficiently

 

By default, an enum is an int, and therefore, enums are 32 bits in size, which gives you a range of values of

 -2,147,483,648 through 2,147,483,647. If you’re going to use only small values for enum members, memory will be wasted if each variable takes up 32 bits. For this reason, it’s possible to base an enum on any integer type. In the case of our WeekDay example, all our values can quite happily fit into 1 byte. You could base the enum on a char, as shown here:

// WeekDay variables are one byte in size

enum class WeekDay:char

{

    Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

};

Quick Reference

 

To

Do this

Create a struct.

Use value struct, followed by the name of the struct and the body in braces, followed by a semicolon. For example:

 

value struct Point3D

{

    int x, y, z;

};

 

Initialize struct members.

Create a constructor, which is a function that has the same name as the struct. For example:

 

value struct Point3D

{

    int x, y, z;

    Point3D(int xVal, int yVal, int zVal)

    {

        x=xVal;

        y=yVal;

        z=zVal;

    }

};

 

You can also use an aggregate initializer:

 

Point3D p1 = { 10, 20, 30 };

 

Access struct members.

Use the dot notation. For example:

 

p1.x = 10;

myPerson.DOB.dd = 20;

 

Create an enum.

Use value enum, followed by the name of the enum and the body in braces, followed by a semicolon. For example:

 

value enum Seasons

{ Spring, Summer, Autumn, Winter };

 

Control the values used for enum members.

Assign values to the members in the enum definition. For example:

 

value enum Seasons

{ Spring=1, Summer, Autumn, Winter };

 

Base enums on other integer types.

Put a colon and the type name after the enum name. For example:

 

value enum Seasons : char

{ Spring, Summer, Autumn, Winter };

 

 

Table 2

 

 

 

 

Part 1 | Part 2 | Part 3 | Part 4

 


 

< C++ .NET Value Type 3 | Main | C++ .NET Operator Overloading 1 >