Home

Classes and Methods

 

Methods Arguments

Like regular functions, the methods of a class can use some arguments to carry their assignments. To pass an argument to a method, simply type it in the parentheses. By design, the member variables of an object are accessible to the methods of the same object. This means that you do not have to pass their equivalents to your methods.

Practical LearningPractical Learning: Introducing Data Reading

  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 ElectroStore2 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
        {
        private:
            long        nbr;
            __wchar_t ^ cat;
            String    ^ mk;
            String    ^ mdl;
            double      discount;
            double      price;
    
        public:
            inline long        GetItemNumber();
            inline __wchar_t ^ GetCategory();
            inline String    ^ GetMake();
            inline String    ^ GetModel();
            inline double      GetDiscountRate();
            inline double      GetUnitPrice();
        };
    }
  9. To create a source file, on the main menu, click Project -> Add New Item...
  10. In the Templates list, click C++ File (.cpp)
  11. Set the Name to StoreItem and press Enter
  12. Complete the file as follows:
     
    #include "StoreItem.h"
    using namespace System;
    
    namespace ElectronicsStore
    {
        inline long CStoreItem::GetItemNumber()
        {
    	return nbr;
        }
    
        inline __wchar_t ^ CStoreItem::GetCategory()
        {
    	return cat;
        }
    
        inline String ^ CStoreItem::GetMake()
        {
    	return mk;
        }
    
        inline String ^ CStoreItem::GetModel()
        {
    	return mdl;
        }
    
        inline double CStoreItem::GetDiscountRate()
        {
    	return discount / 100;
        }
    
        inline double CStoreItem::GetUnitPrice()
        {
    	return price;
        }
    }
  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;
    
    int main()
    {
        String ^ strTitle = L"=-= Nearson Electonics =-=\n"
    		        L"******* Store Items ******";
        CStoreItem ^ sItem = gcnew CStoreItem;    
    
        Console::WriteLine();
        return 0;
    }
  16. Save all

Constant Arguments

In previous lessons, we learned that when a function received an argument that it didn't modify, the argument should be declared as constant. This allows the compiler to make sure that the argument would not be modified. The same technique applies to an argument used by a method of a class.

To declare an argument of an object’s method as constant, type the const keyword on the left of the argument’s data type. Consider a box object as follows:

Box

We would like to know the area of each side because different things will be displayed on each side and we need to know how much space is available. If we were dealing with a rectangle, we would just declare an area method as follows:

double FaceArea();

On a box (rectangular parallelepiped), we have three rectangle types that represent the six faces. We can declare one method that takes any two sides and calculates their area. Such a method would be declared as follows:

double FaceArea(double side1, double side2);

We can define it as follows:

public value struct CBox
{
    double FaceArea(double length, double height)
    {
        double area = length * height;
        return area;
    }
};

Notice that the method doesn't modify the values of the arguments it uses. Therefore, they should be declared as constants. To declare each as constant, you would change the declaration of the method as follows:

double Area(const double side1, const double side2);

Here is an example of a class with methods that take constant arguments:

using namespace System;

public value class CBox
{
public:
    double FaceArea(const double length, const double height)
    {
        double area = length * height;
        return area;
    }
    double TopArea(const double length, const double width)
    {
        return length * width;
    }

    double RightArea(const double height, const double width)
    {
        return height * width;
    }
};

int main()
{
    CBox ^ box = gcnew CBox;

    const double L = 35.85;
    const double H = 28.46;
    const double W = 22.08;

    Console::WriteLine(" -=- Box Areas -=-");
    Console::WriteLine("Top:   {0}", box->TopArea(L, W));
    Console::WriteLine("Face:  {0}", box->FaceArea(L, H));
    Console::WriteLine("Right: {0}", box->RightArea(H, W));
    
    return 0;
}

This would produce:

-=- Box Areas -=-
Top:   791.568
Face:  1020.29
Right: 628.397
Press any key to continue...
 

Practical LearningPractical Learning: Passing Constant Arguments

  1. Access the StoreItem.h header file
  2. To create methods with constant arguments, change the file as follows:
     
    #pragma once
    using namespace System;
    
    namespace ElectronicsStore
    {
        public ref class CStoreItem
        {
        private:
            long        nbr;
            __wchar_t ^ cat;
            String    ^ mk;
            String    ^ mdl;
            double      discount;
            double      price;
    
    	public:
            inline long        GetItemNumber();
            inline void        SetItemNumber(const long number);
            inline __wchar_t ^ GetCategory();
            inline void        SetCategory(__wchar_t ^ category);
            inline String    ^ GetMake();
            inline void        SetMake(String ^ make);
            inline String    ^ GetModel();
            inline void        SetModel(String ^ model);
            inline double      GetDiscountRate();
            inline void        SetDiscountRate(const double discountRate);
            inline double      GetUnitPrice();
            inline void        SetUnitPrice(const double unitPrice);
        };
    }
  3. Access the StoreItem.cpp source file
  4. To define methods that take constant arguments, implement the new methods as follows:
     
    #include "StoreItem.h"
    using namespace System;
    
    namespace ElectronicsStore
    {
        inline long CStoreItem::GetItemNumber()
        {
            return nbr;
        }
    
        inline void CStoreItem::SetItemNumber(const long number)
        {
    	this->nbr = number;
        }
    
        inline __wchar_t ^ CStoreItem::GetCategory()
        {
    	return cat;
        }
    
        inline void CStoreItem::SetCategory(__wchar_t ^ category)
        {
    	this->cat = category;
        }
    
        inline String ^ CStoreItem::GetMake()
        {
    	return mk;
        }
    
        inline void CStoreItem::SetMake(String ^ make)
        {
    	this->mk = make;
        }
    
        inline String ^ CStoreItem::GetModel()
        {
    	return mdl;
        }
    
        inline void CStoreItem::SetModel(String ^ model)
        {
    	this->mdl = model;
        }
    
        inline double CStoreItem::GetDiscountRate()
        {
    	return discount / 100;
        }
    
        inline void CStoreItem::SetDiscountRate(const double discountRate)
        {
    	this->discount = discountRate;
        }
    
        inline double CStoreItem::GetUnitPrice()
        {
    	return price;
        }
    
        inline void CStoreItem::SetUnitPrice(const double unitPrice)
        {
            this->price = unitPrice;
        }
    }
  5. Access the Exercise.cpp source file
  6. To use the new methods, change the file as follows:
     
    #include "StoreItem.h"
    
    using namespace System;
    using namespace ElectronicsStore;
    
    CStoreItem ^ CreateStoreItem();
    void DescribeStoreItem(CStoreItem ^ %);
    
    int main()
    {
        String ^ strTitle = L"=-= Nearson Electonics =-=\n"
    		                L"******* Store Items ******";
        CStoreItem ^ storeItem = CreateStoreItem();       
    
        Console::WriteLine();
        Console::WriteLine(strTitle);
        DescribeStoreItem(storeItem);
    
        Console::WriteLine();
        return 0;
    }
    
    CStoreItem ^ CreateStoreItem()
    {
        long        number;
        __wchar_t ^ category;
        String    ^ make;
        String    ^ model;
        double      discount;
        double      price;
    
        Console::WriteLine(L"To create a store item, enter its information");
        Console::Write(L"Item Number: ");
        number = long::Parse(Console::ReadLine());
        Console::WriteLine(L"Category");
        Console::WriteLine(L"A - Audio Cables");
        Console::WriteLine(L"B - Batteries");
        Console::WriteLine(L"C - Cell Phones and Accessories");
        Console::WriteLine(L"D - Bags and Cases");
        Console::WriteLine(L"H - Headphones");
        Console::WriteLine(L"M - Digital Cameras");
        Console::WriteLine(L"O - Cables and Connectors");
        Console::WriteLine(L"P - PDAs and Accessories");
        Console::WriteLine(L"T - Telephones and Accessories");
        Console::WriteLine(L"S - Surge Protector");
        Console::Write(L"Your Choice? ");
        category = __wchar_t::Parse(Console::ReadLine());
        Console::Write(L"Make         ");
        make = Console::ReadLine();
        Console::Write(L"Model:       ");
        model = Console::ReadLine();
        Console::Write(L"Discount Applied (Enter 0 to 100, 0 if no discount): ");
        discount = double::Parse(Console::ReadLine());
        Console::Write(L"Unit Price:  ");
        price = double::Parse(Console::ReadLine());
    
        CStoreItem ^ sItem = gcnew CStoreItem;
        sItem->SetItemNumber(number);
        sItem->SetCategory(category);
        sItem->SetMake(make);
        sItem->SetModel(model);
        sItem->SetDiscountRate(discount);
        sItem->SetUnitPrice(price);
    
        return sItem;
    }
    
    void DescribeStoreItem(CStoreItem ^ %item)
    {
        Console::WriteLine(L"Store Item Description");
        Console::WriteLine(L"Item Number:   {0}", item->GetItemNumber());
        Console::WriteLine(L"Category:      {0}", item->GetCategory());
        Console::WriteLine(L"Make           {0}", item->GetMake());
        Console::WriteLine(L"Model:         {0}", item->GetModel());
        Console::WriteLine(L"Discount Rate: {0:P}", item->GetDiscountRate());
        Console::WriteLine(L"Unit Price:    {0:C}", item->GetUnitPrice());
    }
  7. Execute the application to test it. Here is an example:
     
    To create a store item, enter its information
    Item Number: 204066
    Category
    A - Audio Cables
    B - Batteries
    C - Cellphones and Accessories
    D - Bags and Cases
    H - Headphones
    M - Digital Cameras
    O - Cables and Connectors
    P - PDAs and Accessories
    T - Telephones and Accessories
    S - Surge Protector
    Your Choice? P
    Make         HP
    Model:       iPAQ hw6510 Mobile Messenger
    Discount Applied (Enter 0 to 100, 0 if no discount): 15
    Unit Price:  585.95
    
    =-= Nearson Electonics =-=
    ******* Store Items ******
    Store Item Description
    Item Number:   204066
    Category:      P
    Make           HP
    Model:         iPAQ hw6510 Mobile Messenger
    Discount Rate: 15.00 %
    Unit Price:    $585.95
    
    Press any key to continue . . .
    PDA
  8. Close the DOS window

Private Methods

As you might have found out, some of the methods of a class are exclusively used to carry assignments. The external functions or other objects don't call such methods and don't communicate with them. If you create a class and know that a particular method is not used to transfer data to the client functions, you can declare such a method as private, just like you would do with a member variable.

To declare a method as private, include it in a private: section of the object. To implement it, follow the same rules we have learned about implementing the methods of an object. You must keep in mind (which will also be very important when we learn about inheritance) is that this method is not available to the outside world. Here is an example:

using namespace System;

public value class CBox
{
private:
	double Length;
	double Height;
	double Width;

public:
	CBox ^ Create();
	void Show();

private:
    double FaceArea()
    {
        return Length * Height;
    }
    double TopArea()
    {
        return Length * Width;
    }

    double  RightArea()
    {
        return Height * Width;
    }
};

CBox ^ CBox::Create()
{
    this->Length = 35.85;
    this->Height = 28.46;
    this->Width  = 22.08;

    return *this;
}

void CBox::Show()
{
    Console::WriteLine(" -=- Box Areas -=-");
    Console::WriteLine("Top:   {0}", this->TopArea());
    Console::WriteLine("Face:  {0}", this->FaceArea());
    Console::WriteLine("Right: {0}", this->RightArea());
}

int main()
{
    CBox ^ box = gcnew CBox;
    CBox ^ one = box->Create();

    one->Show();
    
    Console::WriteLine();
    return 0;
}

Protected Methods

A public method is one that can be accessed outside of its class. A private method is one that cannot be accessed outside of its class. When using inheritance, if you want to create a method that only derived classes can access, put that method in a protected section that is preceded with protected:.

 

Previous Copyright © 2006-2007 FunctionX, Inc. Next