Home

Introduction to the Methods of a Class

 

Methods Fundamentals

Like a variable, a function can be made a member of a class. This allows a class to perform its own assignments and/or better manage its behavior. These tasks cannot be handled by a regular member variable. When a function is a member of a class, that function is called a method.

To create a method, you start like a normal function but you include it in the body of the class. Here is an example:

public value class CCar
{
private:
    String ^ Make;
    String ^ Model;
    int      Doors;
    int      Year;
    double   Price;
	
public:
    void Build();
};

In the same way, you can add as many methods as you judge necessary for your class. Here is an example:

public value class CCar
{
private:
    String ^ Make;
    String ^ Model;
    int      Doors;
    int      Year;
    double   Price;
	
public:
    void Build();
    void Show();
};

Practical LearningPractical Learning: Introducing Methods

  1. To start a new project, on the main menu, click File -> New -> Project...
  2. On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
  3. In the Name box, replace the string with ElectroStore1 and click OK
  4. On the main menu, click Project -> Add New Item...
  5. To create a header file, in the Templates list, click Header File (.h)
  6. Set the Name to StoreItem and click Add
  7. Complete the file as follows:
     
    #pragma once
    using namespace System;
    
    namespace ElectronicsStore
    {
        public ref class CStoreItem
        {
        private:
            long        ItemNumber;
            __wchar_t ^ Category;
            String ^    Make;
            String ^    Model;
            double      DiscountRate;
            double      UnitPrice;
        };
    }
  8. To create a source file, in the Templates list, click C++ File (.cpp)
  9. Set the Name to Exercise and click Add
  10. 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 ^ item = gcnew CStoreItem;    
    
        Console::WriteLine(strTitle);
    
        Console::WriteLine();
        return 0;
    }
  11. Execute the application to test it. This would produce:
     
    =-= Nearson Electonics =-=
    ******* Store Items ******
    
    Press any key to continue . . .
  12. Close the DOS window

Method Local Definition

There are at least two techniques you can use to implement a method. To implement a method in the class where the method is declared, use the same techniques we used to define regular functions. When a method is a class' member, it has access to the member variables of the same class; this means that you don't need to pass the variables as arguments; you can just use any of them as if it were supplied. Here is an example:

public value class CCar
{
private:
    String ^ Make;
    String ^ Model;
    int      Doors;
    int      Year;
    double   Price;
	
public:
    void Build()
    {
        Console::Write(L"Enter Make:  ");
        Make = Console::ReadLine();
        Console::Write(L"Enter Model: ");
        Model = Console::ReadLine();
        Console::Write(L"# of Doors:  ");
        Doors = int::Parse(Console::ReadLine());
        Console::Write(L"Year Made:   ");
        Year = int::Parse(Console::ReadLine());
        Console::Write(L"Enter Price: ");
        Price = double::Parse(Console::ReadLine());
    }

    void Show();
};

To call a method from a declared handle of a class, you can use the -> operator just as you would proceed to access a member of a class. Here is an example:

using namespace System;

public value class CCar
{
private:
    String ^ Make;
    String ^ Model;
    int      Doors;
    int      Year;
    double   Price;
	
public:
    void Build()
    {
        Console::WriteLine(L"Enter Car Information");
        Console::Write(L"Enter Make:  ");
        Make = Console::ReadLine();
        Console::Write(L"Enter Model: ");
        Model = Console::ReadLine();
        Console::Write(L"# of Doors:  ");
        Doors = int::Parse(Console::ReadLine());
        Console::Write(L"Year Made:   ");
        Year = int::Parse(Console::ReadLine());
        Console::Write(L"Enter Price: ");
        Price = double::Parse(Console::ReadLine());
    }
};

int main()
{
    CCar ^ vehicle = gcnew CCar;
	
    vehicle->Build();

    Console::WriteLine();
    return 0;
}
 

Practical LearningPractical Learning: Implementing a Method Locally

  1. To implement a method locally, access the StoreItem.h file and create the following method:
     
    #pragma once
    using namespace System;
    
    namespace ElectronicsStore
    {
        public ref class CStoreItem
        {
        private:
            long     ItemNumber;
            __wchar_t ^ Category;
            String ^ Make;
            String ^ Model;
            double   DiscountRate;
            double   UnitPrice;
    
        public:
            void CreateStoreItem()
    	{
    	Console::WriteLine(L"To create a store item, enter its information");
    	    Console::Write(L"Item Number: ");
    	    ItemNumber = 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 if no discount): ");
    	    DiscountRate = double::Parse(Console::ReadLine());
    	    Console::Write(L"Unit Price:  ");
    	    UnitPrice = double::Parse(Console::ReadLine());
    	}
        };
    }
  2. Save the file

Method Global Definition

Instead of using the body of a class, you can also define a method outside of its class. To do this, start with void or the return type of the method, followed by the name of the class, followed by the :: operator, followed by the name of the method, followed by its parentheses, followed by the body of the method delimited by its curly brackets. The method must have been declared in the body of the class. Here is an example:

using namespace System;

public value class CCar
{
private:
    String ^ Make;
    String ^ Model;
    int      Doors;
    int      Year;
    double   Price;
	
public:
    void Build()
    {
        Console::WriteLine(L"Enter Car Information");
        Console::Write(L"Enter Make:  ");
        Make = Console::ReadLine();
        Console::Write(L"Enter Model: ");
        Model = Console::ReadLine();
        Console::Write(L"# of Doors:  ");
        Doors = int::Parse(Console::ReadLine());
        Console::Write(L"Year Made:   ");
        Year = int::Parse(Console::ReadLine());
        Console::Write(L"Enter Price: ");
        Price = double::Parse(Console::ReadLine());
    }

    void Show();
};

void CCar::Show()
{
    Console::WriteLine(L"\nCar Characteristics");
    Console::WriteLine(L"Make:  {0}", Make);
    Console::WriteLine(L"Model: {0}", Model);
    Console::WriteLine(L"Doors: {0}", Doors);
    Console::WriteLine(L"Year:  {0}", Year);
    Console::WriteLine(L"Value: {0:C}", Price);
}

int main()
{
    CCar ^ vehicle = gcnew CCar;
	
    vehicle->Build();

    vehicle->Show();

    Console::WriteLine();
    return 0;
}

You can use a mixture of local and global method definitions. Make sure that each method is implemented only once, either locally, in the object, or globally, outside of the object.

By tradition, when defined globally, the methods of a class are implemented in the associated source file of the header file of the class.

 

Practical LearningPractical Learning: Implementing Methods Globally

  1. Change the StoreItem.h header file as follows:
     
    #pragma once
    using namespace System;
    
    namespace ElectronicsStore
    {
        public ref class CStoreItem
        {
        private:
            long        ItemNumber;
            __wchar_t ^ Category;
            String    ^ Make;
            String    ^ Model;
            double      DiscountRate;
            double      UnitPrice;
    
        public:
    	void CreateStoreItem();
    	void ItemDescription();
        };
    }
  2. To create a source file, in the Templates list, click C++ File (.cpp)
  3. Set the Name to StoreItem and click Add
  4. Complete the file as follows:
       
    #include "StoreItem.h"
    using namespace System;
    
    namespace ElectronicsStore
    {
        void CStoreItem::CreateStoreItem()
       {
    	Console::WriteLine(L"To create a store item, enter its information");
    	Console::Write(L"Item Number: ");
    	ItemNumber = 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 if no discount): ");
    	DiscountRate = double::Parse(Console::ReadLine());
    	Console::Write(L"Unit Price:  ");
    	UnitPrice = double::Parse(Console::ReadLine());
        }
    
        void CStoreItem::ItemDescription()
        {
            Console::WriteLine(L"Store Item Description");
    	Console::WriteLine(L"Item Number:   {0}", ItemNumber);
    	Console::WriteLine(L"Category:      {0}", Category);
    	Console::WriteLine(L"Make           {0}", Make);
    	Console::WriteLine(L"Model:         {0}", Model);
    	Console::WriteLine(L"Discount Rate: {0}", DiscountRate);
    	Console::WriteLine(L"Unit Price:    {0}", UnitPrice);
        }
    }
  5. Access the Exercise.cpp file and change it as follows:
     
    #include "StoreItem.h"
    
    using namespace System;
    using namespace ElectronicsStore;
    
    int main()
    {
        String ^ strTitle = L"=-= Nearson Electonics =-=\n"
    		        L"******* Store Items ******";
        CStoreItem ^ item = gcnew CStoreItem;    
    
        item->CreateStoreItem();
        Console::WriteLine();
        Console::WriteLine(strTitle);
        item->ItemDescription();
    
        Console::WriteLine();
        return 0;
    }
  6. Execute the application to test it. Here is an example:
     
    To create a store item, enter its information
    Item Number: 624406
    Category
    A - Audio Cables
    B - Batteries
    C - Cell Phones 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? M
    Make         Canon
    Model:       Powershot A620
    Discount Applied (Enter 0 to 100, 0 if no discount): 20
    Unit Price:  320.95
    
    =-= Nearson Electonics =-=
    ******* Store Items ******
    Store Item Description
    Item Number:   624406
    Category:      M
    Make           Canon
    Model:         Powershot A620
    Discount Rate: 20.00 %
    Unit Price:    $320.95
    
    Press any key to continue . . .
  7. Close the DOS window

Inline Methods

When a method is implemented locally, that is, in the body of a class, it is referred to as inline. To re-enforce this, you can precede its name with the inline keyword when declaring the method in the class. Here is an example:

public value class CCar
{
private:
    String ^ Make;
    String ^ Model;
    int      Doors;
    int      Year;
    double   Price;
	
public:
    void inline Build()
    {
        . . .
    }

    void Show();
};

If you define a method globally but you want it to be processed as inline, precede its name with the inline keyword. Here is an example:

public value class CCar
{
private:
    String ^ Make;
    String ^ Model;
    int      Doors;
    int      Year;
    double   Price;
	
public:
    void inline Build()
    {
        . . .
    }

    void Show();
};

void inline CCar::Show()
{
    Console::WriteLine(L"\nCar Characteristics");
    Console::WriteLine(L"Make:  {0}", Make);
    Console::WriteLine(L"Model: {0}", Model);
    Console::WriteLine(L"Doors: {0}", Doors);
    Console::WriteLine(L"Year:  {0}", Year);
    Console::WriteLine(L"Value: {0:C}", Price);
}

You can choose which method(s) would be inline and which one(s) would not. When implementing the method, you can precede the method with the inline keyword. You can also omit the inline keyword in the class but use it when defining the method.

After defining the method of class, whether locally or globally, any method can call another without using an access operator. This allows an class’ methods to exchange information among themselves easily. Furthermore, unlike regular functions where a function must be declared prior to another function calling it, the methods of a class don't follow that rule: one method can call another method before or after the other has been implemented, as long as it is defined somewhere in the program.

 

Previous Copyright © 2006-2007 FunctionX, Inc. Next