Home

Class and Self Return

 

Introduction

When it comes to returning a class after processing it, you have two main alternatives: you can get a class to be returned by an external function or you can create a method that returns its own type of class. To proceed, first declare a method by specifying its return type as the class itself. Because a managed class can only be declared as a handle, the return type must be specified as a handle. Here is an example:

public value class CHouse
{
public:
	__wchar_t TypeOfHome;
	int NumberOfBedrooms;
	double NumberOfBathrooms;
	Byte Stories;
	int YearBuilt;
	double Value;

	CHouse ^ Create();
};

In the body of the method, proceed as you see fit. As done with other functions, before the end of the method, you must remember to return a handle to the class. Here is an example:

CHouse ^ CHouse::Create()
{
    CHouse ^ home = gcnew CHouse;

    home->TypeOfHome = L's';
    home->NumberOfBedrooms = 4;
    home->NumberOfBathrooms = 3.5;
    home->Stories = 2;
    home->YearBuilt = 2002;
    home->Value = 455960;

    return home;
}

After defining a self returning method, you can call it like you would any normal method. Here is an example:

using namespace System;

public value class CHouse
{
public:
	__wchar_t TypeOfHome;
	int NumberOfBedrooms;
	double NumberOfBathrooms;
	Byte Stories;
	int YearBuilt;
	double Value;

	CHouse ^ Create();
	void Show();
};

int main()
{
	CHouse ^ House2002 = gcnew CHouse;
	CHouse ^ Property = House2002->Create();
	Property->Show();

        Console::WriteLine();
	return 0;
}

CHouse ^ CHouse::Create()
{
    CHouse ^ home = gcnew CHouse;

    home->TypeOfHome = L's';
    home->NumberOfBedrooms = 4;
    home->NumberOfBathrooms = 3.5;
    home->Stories = 2;
    home->YearBuilt = 2002;
    home->Value = 455960;

    return home;
}

this Pointer

C++ proposes an alternative to returning a class from one of its methods. Instead of explicitly declaring a variable when implementing a method that returns the same class, the compiler simply needs to know what object you want to return: the object that called the method or a newly declared one. If you want to return the same object, you can use a special pointer called this.

As its name implies, the this pointer is a self referencing object, which means it allows you to designate the object that is making the call as the same object you are referring to. Using the this pointer is a technique that allows you to perform any necessary operation on an object without the help of an external function and returning the same object.

Suppose you want to transform the Create() method of the CHouse class above so it would return the same variable that calls it. Because the method will return the same object, you don't need to declare a local variable to hold the changed variable. Since the member variables of the class will be modified, the method cannot be declared as a constant.

When implementing this method, the values of the variables will certainly be modified to implement whatever behavior you want. To return the same object, the this object must be called as a pointer, with *this. This would be done as follows:

CHouse ^ CHouse::Create()
{
    return *this;
}

One way you can use a method that self-returns its class is to initialize its member variables. Since the method returns its class, you can therefore return a pointer to this. Here is an example:

using namespace System;

public value class CHouse
{
public:
	__wchar_t TypeOfHome;
	int NumberOfBedrooms;
	double NumberOfBathrooms;
	Byte Stories;
	bool HasGarage;
	int YearBuilt;
	double Value;

	CHouse ^ Create();
	void Show();
};

int main()
{
    CHouse ^ House2002 = gcnew CHouse;
    CHouse ^ Property = House2002->Create();
    Property->Show();

    Console::WriteLine();
    return 0;
}

CHouse ^ CHouse::Create()
{
    TypeOfHome        = L'C';
    NumberOfBedrooms  = 1;
    NumberOfBathrooms = 1.0;
    Stories           = 1;
    HasGarage         = false;
    YearBuilt         = 1960;
    Value             = 100000;

    return *this;
}

void CHouse::Show()
{
    . . .
}

Instead of returning a handle, since the method that returns the this pointer returns it as a pointer, you can make it return a tracking reference. Here is an example:

CHouse % CHouse::Create()
{
    TypeOfHome        = L'C';
    NumberOfBedrooms  = 1;
    NumberOfBathrooms = 1.0;
    Stories           = 1;
    HasGarage         = false;
    YearBuilt         = 1960;
    Value             = 100000;

    return *this;
}

This version of the method would produce the same effect as the previous one.

Practical LearningPractical Learning: Using the this Pointer

  1. Access the StoreItem.cpp source file
  2. To use the this pointer, change the members of the class 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: ");
    	this->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? ");
    	this->Category = __wchar_t::Parse(Console::ReadLine());
    	Console::Write(L"Make         ");
    	this->Make = Console::ReadLine();
    	Console::Write(L"Model:       ");
    	this->Model = Console::ReadLine();
       Console::Write(L"Discount Applied (Enter 0 to 100, 0 if no discount): ");
    	this->DiscountRate = double::Parse(Console::ReadLine());
    	Console::Write(L"Unit Price:  ");
    	this->UnitPrice = double::Parse(Console::ReadLine());
        }
    
        void CStoreItem::ItemDescription()
        {
            Console::WriteLine(L"Store Item Description");
    	Console::WriteLine(L"Item Number:   {0}", this->ItemNumber);
    	Console::WriteLine(L"Category:      {0}", this->Category);
    	Console::WriteLine(L"Make           {0}", this->Make);
    	Console::WriteLine(L"Model:         {0}", this->Model);
        Console::WriteLine(L"Discount Rate: {0:P}", this->DiscountRate / 100);
    	Console::WriteLine(L"Unit Price:    {0:C}", this->UnitPrice);
        }
    }
  3. Execute the application to test it
  4. Close the DOS window
 

Previous Copyright © 2006-2016, FunctionX, Inc. Next