Home

The Properties of a Class

 

Introduction

The members of a class are divided in two main roles. The variables provide storage of data for an object; they also define the characteristics of an object. The methods perform related assignments of a class. Sometimes they receive requests from other objects or functions and provide the appropriate results that the other objects and functions are expecting. For this reason, the other objects and functions from outside the class don't need access to the member variables of an object; if they need anything, they would call a method of the class and let the object know "what they want".

To protect the data of a class, you can hide its member variables, after determining which member variables the other objects would not need access to. To hide a member variable, you can put it in a private section. Here is an example:

Header File: Rectangle.h
#pragma once

public ref class CRectangle
{
private:
    double len;
};
 
Source File: Rectangle.cpp
#include "Rectangle.h"

After making a member variable private, if you want outside classes or functions to access its value, you can create a public method that would act as an intermediary. On the other hand, if you want outside classes or functions to modify the value of that private member variable, you can define a public method that would "negotiate" this interaction. In traditional programming, these types of operations are taken care of by accessory methods.

Practical LearningPractical Learning: Introducing the Properties of a Class

  1. Start Microsoft Visual C++ 2005
  2. On the main menu, click File -> New -> Project...
  3. On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
  4. In the Name box, replace the string with ElectroStore5 and click OK
  5. On the main menu, click Project -> Add New Item...
  6. To create a header file, in the Templates list, click Header File (.h)
  7. Set the Name to StoreItem and click Add
  8. Complete the file as follows:
     
    #pragma once
    using namespace System;
    
    namespace ElectronicsStore
    {
        public ref class CStoreItem
        {
        public:
            // An item whose characteristics are not (yet) known
            CStoreItem(void);
            // An item that is known by its make, model, and unit price
            CStoreItem(long itmNbr, String ^ make,
    		   String ^ model, double unitPrice);
            // An item that is known by its name and unit price
            CStoreItem(long itmNbr, String ^ name, double unitPrice);
            // An item completely defined
            CStoreItem(long itmNbr, __wchar_t category,
    			   String ^ make, String ^ model,
    			   double discountRate, double unitPrice);
            ~CStoreItem();
    
        private:
            long        nbr;
            __wchar_t ^ cat;
            String    ^ mk;
            String    ^ mdl;
    	String    ^ nm;
            double      discount;
            double      price;
    
        public:
            
        };
    }
  9. To create a source file, on the main menu, click Project -> Add New Item...
  10. In the Templates list, click C++ File (.h)
  11. Set the Name to StoreItem and press Enter
  12. Complete the file as follows:
     
    #include "StoreItem.h"
    using namespace System;
    
    namespace ElectronicsStore
    {
        CStoreItem::CStoreItem(void)
    	: nbr(0),
    	  cat(L'U'),
    	  mk(L"Unknown"),
    	  mdl(L"Unspecified"), 
    	  nm(L"N/A"),
    	  discount(0.00),
    	  price(0.00)
        {
        }
    
        CStoreItem::CStoreItem(long itmNbr, String ^ make,
    			   String ^ model, double unitPrice)
    	: nbr(itmNbr), 
    	  cat(L'U'),
    	  mk(make),
    	  mdl(model),
    	  nm(L"N/A"),
    	  discount(0.00),
    	  price(unitPrice)
        {
        }
        
        CStoreItem::CStoreItem(long itmNbr, String ^ name,
    				double unitPrice)
    	: nbr(itmNbr),
    	  cat(L'U'),
    	  mk(L"Unknown"),
    	  mdl(L"Unspecified"),
    	  nm(name),
    	  discount(0.00),
    	  price(unitPrice)
        {
        }
        
        CStoreItem::CStoreItem(long itmNbr, __wchar_t category,
    			   String ^ make, String ^ model,
    			   double discountRate, double unitPrice)
    	: nbr(itmNbr),
    	  cat(category),
    	  mk(make),
    	  mdl(model),
    	  discount(discountRate),
    	  price(unitPrice)
        {
        }
    
        CStoreItem::~CStoreItem()
        {
        }
    }
  13. To create one more source file, on the main menu, click Project -> Add New Item...
  14. In the Templates list, make sure C++ File (.cpp) is selected.
    Set the Name to Exercise and click Add
  15. Complete the file as follows:
     
    #include "StoreItem.h"
    
    using namespace System;
    using namespace ElectronicsStore;
    
    static void DescribeStoreItem(CStoreItem ^ %);
    
    int main()
    {
        String ^ strTitle = L"=-= Nearson Electonics =-=\n"
    		        L"******* Store Items ******";
        Console::WriteLine();
        return 0;
    }
  16. Execute the application to make sure it can compile
  17. Close the DOS window

Reference Methods

Because it cannot perform an assignment, a member variable of a class can only receive a value from the outside world. It can also be vulnerable to outside objects and functions. You can prevent this vulnerability by "hiding" the member variable in a private section. Because you may still want outside objects and functions to interact with the value held by a member variable, you can create an accessory method that corresponds to that variable. One way you can implement such a method is to make it return a reference.

Like a regular function, a method of a class can be created to return a reference or a tracking reference. When creating the method, make sure you type the & or % operator on the left of its name. When implementing the method, in most cases, you can simply return a member variable of the class that is declared with the same data type as the one that the method would return. Here is an example:

Header File: Rectangle.h
#pragma once

public ref class CRectangle
{
private:
	double len;

public:
	double %Length();
};
Source File: Rectangle.cpp
#include "Rectangle.h"

double %CRectangle::Length()
{
	return len;
}

You may remember that a function can only be assigned to a variable. It cannot be assigned a value. In the same way, no value can be assigned to the name of a method. For example, the following code will not compile:

public ref class Circle
{
private:
	double Radius;
public:
	Circle(double rad) { Radius = rad; }
	double Area() { return Radius * Radius * 3.14159; }
};

int main()
{
	Circle circ(24.55);
	double a = 0.00;
	circ.Area() = a;

	return 0;
}

The exception to this rule is with reference methods. If a method returns a reference, it can be assigned a value. Here is an example:

int main()
{
	CRectangle ^ rect = gcnew CRectangle;
	
	rect->Length() = 24.58;

	ShowCharacteristics(rect);
	Console::WriteLine();

	return 0;
}

In the same way, a method that returns a reference can also have its value retrieved. Here is an example:

Source File: Exercise.cpp
#include "Rectangle.h"

using namespace System;

void ShowCharacteristics(CRectangle ^ %recto)
{
	Console::WriteLine(L"Rectangle Characteristics");
	Console::WriteLine(L"Length:    {0}", recto->Length());
}

int main()
{
	CRectangle ^ rect = gcnew CRectangle;
	
	rect->Length() = 24.58;

	ShowCharacteristics(rect);
	Console::WriteLine();

	return 0;
}

This would produce:

Rectangle Characteristics
Length:    24.58

Press any key to continue . . .

Notice that a reference method is assigned a value or a value is assigned to it. In the C++ jargon, this means that a reference method can be either an L-value (left value) or an R-value (right value) in an expression. As mentioned earlier, a regular member variable cannot validate or reject value because it cannot perform an assignment. Like the properties that we will see next, the ability for a reference method to be a left or right operand of an assignment makes it a valuable candidate to validate or reject a value that is meant for a member variable.

A Property

A method is an action that is performed to complement a class. It requires the mechanism of a function: some parentheses and optional arguments. If you declare a private member variable that must interact with the outside world, you must also implement different methods to accomplish different roles. One of the obstacles of a normal method is that it cannot be assigned a value, unless you create it as returning a reference. A property provides a solution to both problems in one object. To be able to play this role, a property must combine the functionalities of a member variable and that of a method. For this reason, there are strict rules you must follow to create a method.

The primary syntax used to create a property is:

modifier property type property_name;

The modifier can be static (or virtual, which we will introduce in the next lessons). The property keyword is required. The property keyword is followed by a data type, which can be one of those we reviewed in Lesson 2. It can also be an enumeration. The data type is followed by the name of the property.

 

Home Copyright © 2006-2007 FunctionX, Inc. Next