CLASSES AND OBJECTS


As previously discussed, objects are instances of classes that are instantiated at runtime. A class, in turn, is a template that defines all the properties, methods, and events required to create an object. Using abstraction, programmers develop the overall design of a class. Using encapsulation, they develop the interface for the class and hide the nonessential details. Programmers can also use polymorphism, via overloading, to any given method of the class to accept different arguments. Finally, they can use inheritance to derive the features and functionality of one class from another.

To use a class, you must instantiate it. This creates an instance of the class that the application can use. The process for doing so differs, depending on what type of class you are using. If, for example, you want to instantiate a Button or Checkbox class (control), you can drag it to your form. Visual C++ takes care of the necessary details automatically. On the other hand, if you want to create a control while your program is running or instantiate your own custom class, you must do so in code.

Creating a New Class

You can create a new class in various ways. First, any time you create a new Visual C++ application, a new class is created for you based on the System::Windows::Forms::Form class. You can control the name of the class by specifying the name of the form. (By default, it is Form1.)

You can also embed a class directly within the form code of your application. There are several types of classes you can use when doing so. The following are some of the most useful ones:

  • value. Provides the most efficient way to represent an object that is mainly composed of data

  • enum. Allows for the specification of an object with a specific series of values

  • ref. Provides the most flexibility when adding a class to your application

Understanding the Value Classes

The value class provides a means to create simple classes.

One of the best uses of the value class is in the creation of custom data types. These types allow you to group related items within a single object. You could use the value class, for instance, to create objects that represent points on a map. The format for defining such a class might look like the following example:

 value class cLocation { public:   Int32 Longitude, Latitude; }; 

The value class is intended to be used like .NET'S fundamental data types, such as Int32 or Double. You can create a custom type. For example, you can declare objects representing your current location:

 cLocation myCurrentLocation; cLocation myHomeLocation, myWorkLocation; 

You can also use such an object just as you would any other data type:

 myCurrentLocation.Longitude = 0; myCurrentLocation.Latitude = 0; 

Understanding Enum Classes

The enum class allows you to enumerate a series of related constant values. This feature can be extremely useful if your application needs to represent important states or events with an easy-to-read label. Enumerated classes are composed of a class name and store labels that represent any constant, unchanging value you want to represent. For example, you can use the code in the following listing to represent different types of playing cards:

 enum class Suit {   Hearts, Clubs, Diamonds, Spades }; 

Enumerated types automatically number themselves sequentially. You can use them without concern for what their underlying values are. But if your application needs enumerated values to map to specific values, you can specify exact values for each element:

 enum class ErrorCode {   LogError = 1001, SystemError = 1005, }; 

To use an enumerated type, you declare a variable using the name of the enum class as the type:

 Suit playerCardSuit; ErrorCode criticalError; 

You can then use the enumerated object you have created in your program just as you might an Int16 or String data type:

 playerCardSuit = Suit::Hearts; criticalError = ErrorCode::SystemError; 

By default, the enum class is based on the Int32 data type. You can change this, however. If you need enumerated types that derive from another fundamental type, you must specify the type after the class name when defining the class:

 enum class Suit : Int16 {       Hearts, Clubs, Diamonds, Spades }; 

Enumerated classes are useful because they save you from having to represent an important, distinct program state with just a number or variable. If you needed to compare a value to an error code, for instance, not only would it be risky to use a number (what if it changed?), but it would make your code harder to read. Enumerated classes allow you to represent important but unchanging information in a way that is readable and consistent throughout your program.

Understanding Ref Classes

The ref class offers the most flexible and powerful features. In fact, you have used a ref class each time you've built a Windows Forms application. Open any project you have created so far (or simply create a new one), and look for the following code near the top of the Form1.h file. You see a line similar to this:

 public ref class Form1 : public System::Windows::Forms::Form 

This line appears complex, but essentially it indicates that Form1 is a ref class. The colon after the Form1 indicates that the form inherits from System::Windows::Forms::Form. To better understand the ref class, let's work with an example. Create a new project and double-click on the form so that Visual C++ generates the Load event function. Add the following code:

 /// <summary> /// Required designer variable. /// </summary> ref class Greeting { private:   String^ message; public:   Greeting()   {     message = gcnew String("Greetings!"):   }   Void ShowMessage( Void )   {     MessageBox::Show( message );   } }; 

Next, add the following code to the form's Load event function:

 private: System::Void Form1_Load(System::Object^ sender,\ System::EventArgs^ e) {     Greeting startUpGreeting;     startUpGreeting.ShowMessage();   } 

Press F5 to run the application. When the Load event handler starts, a Greeting object (called startUpGreeting) is instantiated. Immediately below this line of code, the startUpGreeting's ShowMessage() method is activated. This causes a message box containing a friendlymessage to display. Although the message box isn't fancy, it illustrates how you can use a ref class within your own applications.

Just as you define custom functions for your application, you can create custom methods for your ref class. In fact, because you're writing code within the Form1 ref class already, the rules are the same.

If you consider how detailed your programs have already become at this point, it should be clear that you can make the ref classes within your application just as complex. Classes can be composed of other classes, and large applications can be built on hundreds of such classes. For this reason, as your programs grow more complex, you will need to start separating classes into their own files. This is the better way to add classes to your code, but it does not become necessary until you begin building full-fledged applications. Then it becomes an organizational and readability issue.

Trap 

Be sure to follow your class definitions with a semicolon to avoid compiler errors.




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net