Home

Boolean Variables

 

Introduction

When interacting with a computer, a user submits values to a running application. Some of these values are valid. Some other values must be rejected or changed. To take care of these, the values must be checked, examined, re-examined, etc. The validity of a value is checked against its type. For example, a number can be checked as being equal to another. A condition can be checked as being true. A measure can be checked as to whether it is higher than a certain threshold.

To perform the necessary validations of values, the C++ language provides some symbols, referred to as Boolean operators.

Practical LearningPractical Learning: Introducing Conditions

  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 FlowerShop2 and click OK
  5. On the main menu, click Project -> Add Class...
  6. In the Categories lists, expand Visual C++ and click C++.
    In the Templates list, make sure C++ Class is selected and click Add
  7. Set the Name of the class to CFlower and click Finish
  8. Complete the Flower.h header file as follows:
     
    #pragma once
    using namespace System;
    
    public ref class CFlower
    {
    private:
        int _tp;
        int _clr;
        __wchar_t _arg;
        double   _price;
    
    public:
        property int Type
        {
    	int get() { return _tp; }
    	void set(int tp) { _tp = tp; }
        }
    
        property int Color
        {
    	int get() { return _clr; }
    	void set(int clr) { _clr = clr; }
        }
    
        property __wchar_t Arrangement
        {
    	__wchar_t get() { return _arg; }
    	void set(__wchar_t arg) { _arg = arg; }
        }
    
        property double UnitPrice
        {
    	double get() { return _price; }
    	void set(double price) { _price = price; }
        }
    
    public:
        CFlower(void);
        CFlower(int type);
        CFlower(int type, int color,
                __wchar_t argn, double price);
        ~CFlower();
    };
  9. Complete the Flower.cpp source file as follows:
     
    #include "Flower.h"
    
    CFlower::CFlower(void)
        : _tp(0), _clr(0),
          _arg(L'B'), _price(45.95)
    {
    }
    
    CFlower::CFlower(int type)
        : _tp(type),
          _clr(0),
          _arg(L'B'),
          _price(35.95)
    {
    }
    
    CFlower::CFlower(int type, int color,
    	         __wchar_t argn, double price)
    {
        _tp = type;
        _clr = color;
        _arg = argn;
        _price = price;
    }
    
    CFlower::~CFlower()
    {
    }
  10. On the main menu, click Project -> Add Class...
  11. In the Templates list, make sure C++ Class is selected and click Add
  12. Set the Name of the class to COrderProcessing and click Finish
  13. Complete the OrderProcessing.h header file as follows:
     
    #pragma once
    #include "Flower.h"
    
    ref class COrderProcessing
    {
    private:
        int       _qty;
        CFlower ^ _flr;
    
    public:
        COrderProcessing(void);
        ~COrderProcessing();
    
        property CFlower ^ Flower
        {
    	CFlower ^ get() { return _flr; }
    	void set(CFlower ^ flr) { _flr = flr; }
        }
    
        property int Quantity
        {
    	int get() { return _qty; }
    	void set(int q) { _qty = q; }
        }
    
        double GetTotalPrice();
    };
  14. Complete the OrderProcessing.cpp source file as follows:
     
    #include "OrderProcessing.h"
    
    COrderProcessing::COrderProcessing(void)
    {
        _flr = gcnew CFlower;
    }
    
    COrderProcessing::~COrderProcessing()
    {
        delete _flr;
    }
    
    double COrderProcessing::GetTotalPrice()
    {
        return Quantity * _flr->UnitPrice;
    }
  15. To create one more source file, on the main menu, click Project -> Add New Item...
  16. In the Templates list, make sure C++ File (.cpp) is selected.
    Set the Name to Exercise and click Add
  17. Complete the file as follows:
     
    #include "Flower.h"
    #include "OrderProcessing.h"
    using namespace System;
    
    COrderProcessing ^ CreateFlowerOrder()
    {
        COrderProcessing ^ order = gcnew COrderProcessing;
        int type, color, qty;
        __wchar_t arrangement;
        double price;
    
        Console::WriteLine(L"=======================");
        Console::WriteLine(L"==-=-=Flower Shop=-=-==");
        Console::WriteLine(L"-----------------------");
    
        Console::WriteLine(L"Enter the Type of Flower Order");
        Console::WriteLine(L"1. Roses");
        Console::WriteLine(L"2. Lilies");
        Console::WriteLine(L"3. Daisies");
        Console::WriteLine(L"4. Carnations");
        Console::WriteLine(L"5. Live Plant");
        Console::WriteLine(L"6. Mixed");
        Console::Write(L"Your Choice: ");
        type = int::Parse(Console::ReadLine());
    
        Console::WriteLine(L"Enter the Color");
        Console::WriteLine(L"1. Red");
        Console::WriteLine(L"2. White");
        Console::WriteLine(L"3. Yellow");
        Console::WriteLine(L"4. Pink");
        Console::WriteLine(L"5. Orange");
        Console::WriteLine(L"6. Blue");
        Console::WriteLine(L"7. Lavender");
        Console::WriteLine(L"8. Mixed");
        Console::Write(L"Your Choice: ");
        color = int::Parse(Console::ReadLine());
    
        Console::WriteLine(L"Enter the Type of Arrangement");
        Console::WriteLine(L"U. Bouquet");
        Console::WriteLine(L"V. Vase");
        Console::WriteLine(L"B. Basket");
        Console::WriteLine(L"M. Mixed");
        Console::Write(L"Your Choice: ");
        arrangement = __wchar_t::Parse(Console::ReadLine());
    
        Console::Write(L"Enter the Unit Price: ");
        price = double::Parse(Console::ReadLine());
    
        Console::Write(L"Enter Quantity:       ");
        qty = int::Parse(Console::ReadLine());
    
        CFlower ^ flr = gcnew CFlower(type, color, arrangement, price);
        order->Flower = flr;
        order->Quantity = qty;
    
        return order;
    }
    
    void ShowFlowerOrder(COrderProcessing ^ order)
    {
        Console::WriteLine(L"=======================");
        Console::WriteLine(L"==-=-=Flower Shop=-=-==");
        Console::WriteLine(L"-----------------------");
        Console::WriteLine(L"Flower Type:  {0}", order->Flower->Type);
        Console::WriteLine(L"Flower Color: {0}", order->Flower->Color);
        Console::WriteLine(L"Arrangement:  {0}", order->Flower->Arrangement);
        Console::WriteLine(L"Price:        {0:C}", order->Flower->UnitPrice);
        Console::WriteLine(L"Quantity:     {0}", order->Quantity);
        Console::WriteLine(L"Total Price:  {0:C}", order->GetTotalPrice());
        Console::WriteLine(L"=======================");
    }
    
    int main()
    {
        COrderProcessing ^ flower = CreateFlowerOrder();
        ShowFlowerOrder(flower);
    
        Console::WriteLine();
        return 0;
    }
  18. Execute the application and test it. Here is an example:
     
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Enter the Type of Flower Order
    1. Roses
    2. Lilies
    3. Daisies
    4. Carnations
    5. Live Plant
    6. Mixed
    Your Choice: 2
    Enter the Color
    1. Red
    2. White
    3. Yellow
    4. Pink
    5. Orange
    6. Blue
    7. Lavender
    8. Mixed
    Your Choice: 4
    Enter the Type of Arrangement
    U. Bouquet
    V. Vase
    B. Basket
    M. Mixed
    Your Choice: B
    Enter the Unit Price: 65.85
    Enter Quantity:       3
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  2
    Flower Color: 4
    Arrangement:  B
    Price:        $65.85
    Quantity:     3
    Total Price:  $197.55
    =======================
    
    Press any key to continue . . .
  19. Close the DOS window

Declaring a Boolean Variable

A variable is referred to as Boolean if it can hold a value that is either true or false. To declare a Boolean variable, you can use the bool keyword. Here is an example:

using namespace System;

int main()
{
    bool drinkingUnderAge;

    return 0;
}

Alternatively, you can declare a Boolean variable using the Boolean data type. The Boolean data type is part of the System namespace. Here is an example:

using namespace System;

int main()
{
    bool drinkingUnderAge;
    Boolean TheFloorIsCoveredWithCarpet;

    return 0;
}

To display the value of a Boolean variable on the console, you can type its name in the parentheses of the Write() or the WriteLine() methods of the Console class. After the variable has been declared, the compiler initializes it with a false value. This can be demonstrated in the following program:

Bambou
using namespace System;

int main()
{
    bool drinkingUnderAge;

    Console::WriteLine(L"Drinking Under Age: ");
    Console::WriteLine(drinkingUnderAge);

    return 0;
}

This would produce:

Drinking Under Age: False
Press any key to continue . . .

As you can see, by default, a Boolean variable is initialized with false when it is declared. You can initialize the variable with true or false to make sure you know its initial value. Here is an example:

using namespace System;

int main()
{
    bool drinkingUnderAge = true;

    Console::WriteLine(L"Drinking Under Age: ");
    Console::WriteLine(drinkingUnderAge);

    return 0;
}

At any time and when you judge it necessary, you can change the value of the Boolean variable by assigning it a true or false value. Here is an example:

using namespace System;

int main()
{
    bool drinkingUnderAge = true;

    Console::WriteLine(L"Drinking Under Age: ");
    Console::WriteLine(drinkingUnderAge);

    drinkingUnderAge = false;

    Console::WriteLine(L"Drinking Under Age: ");
    Console::WriteLine(drinkingUnderAge);

    return 0;
}

This would produce:

Drinking Under Age: True
Drinking Under Age: False
Press any key to continue . . .

Retrieving the Value of a Boolean Variable

As reviewed for the other data types in Lesson 8, you can request the value of a Boolean variable from the user. In this case, the user must type either True (or true) or False (or false) and you can retrieve it using the Read() or the ReadLine() methods of the Console class. Here is an example:

using namespace System;

int main()
{
    bool drivingUnderAge = false;

    Console::WriteLine(L"Were you driving under age?");
    Console::Write(L"If Yes, enter True. Otherwise enter False: ");
    drivingUnderAge = bool::Parse(Console::ReadLine());

    Console::WriteLine(L"\nWas Driving Under Age: {0}\n", drivingUnderAge);

    return 0;
}

Here is an example of running the program:

Were you driving under age?
If Yes, enter True. Otherwise enter False: true

Was Driving Under Age: True

Press any key to continue . . .

In Windows programming, to expect the user to enter a specify a value of being true or false, the operating system provides a control named CheckBox.

 

Creating a Boolean Member Variable

Like the other types of variables we used in previous lessons, a Boolean variable can be a member of a class. You declare it like any other variable, using the bool keyword or the Boolean data type. Here is an example:

public ref class CHouse
{
public:
	__wchar_t TypeOfHome;
	int    Bedrooms;
	float  Bathrooms;
	Byte   Stories;
	bool   HasCarGarage;
	int    YearBuilt;
	double Value;
};

 

Creating a Boolean Variable

When initializing an object that has a Boolean variable as a member, simply assign true or false to the variable. In the same way, you can retrieve or check the value that a Boolean member variable is holding by simply accessing it. Here are examples:

using namespace System;

public ref class CHouse
{
public:
	__wchar_t TypeOfHome;
	int Bedrooms;
	float Bathrooms;
	Byte Stories;
	bool HasCarGarage;
	int YearBuilt;
	double Value;
};

int main()
{
	CHouse ^ condominium = gcnew CHouse;

	condominium->HasCarGarage = false;
	condominium->YearBuilt = 2002;
	condominium->Bathrooms = 1.5F;
	condominium->Stories = 18;
	condominium->Value = 155825;
	condominium->Bedrooms = 2;
	condominium->TypeOfHome = L'C';

	Console::WriteLine(L"Type of Home:        ");
	Console::WriteLine(condominium->TypeOfHome);
	Console::WriteLine(L"Number of Bedrooms:  ");
	Console::WriteLine(condominium->Bedrooms);
	Console::WriteLine(L"Number of Bathrooms: ");
	Console::WriteLine(condominium->Bathrooms);
	Console::WriteLine(L"Number of Stories:   ");
	Console::WriteLine(condominium->Stories);
	Console::WriteLine(L"Year Built:          ");
	Console::WriteLine(condominium->YearBuilt);
	Console::WriteLine(L"Has Car Garage:      ");
	Console::WriteLine(condominium->HasCarGarage);
	Console::WriteLine(L"Monetary Value:      ");
	Console::WriteLine(condominium->Value);

	Console::WriteLine();
	return 0;
}

This would produce:

Type of Home:        C
Number of Bedrooms:  2
Number of Bathrooms: 1
Number of Stories:   18
Year Built:          2002
Has Car Garage:      False
Monetary Value:      155825

Press any key to continue . . .

Boolean Arguments

Like parameters of the other types, you can pass an argument of type bool or Boolean to a function. Such an argument would be treating as holding a true or false value.

When creating a Windows control, after using the control, it must be destroyed. In C++, this is traditionally done using the delete operator in the destructor of the parent or host of the control, which could be a form. Another detail of Windows controls is that they use or consume computer resources during their lifetime. When the controls are not used anymore, such as when their application closes, these resources should be freed and given back to the operating system to make them available to other applications. This task can be performed using the Dispose() method to the Control class, which can then be overridden by its child controls. The syntax of the Control.Dispose() method is:

protected: void Dispose(bool disposing);

This method takes one argument, disposing, that indicates how the resources would be released. If this argument is passed with a false value, only the unmanaged resources would be released. If it is passed as true, then both managed and unmanaged resources would be released.

During design, we saw that, if you have added a control to your application but you don't want that control anymore, you could delete it. In some rare cases, you may also want to allow the user to delete a control (instead of hiding it). When a control is deleted, the Control::ControlRemoved event is fired. The syntax of this event is:

public: event ControlEventHandler^ ControlRemoved;

This event is carried by a ControlEventHandler delegate through the ControlEventArgs class.

A Boolean Property

A property can be created as a Boolean type. To do this, first specify its data type as bool. When treating the property, make sure its get() accessory returns a Boolean type. If its a write property, make sure you pass a Boolean argument to its set() member.

Practical LearningPractical Learning: Creating a Boolean Property

  1. To create a Boolean property, change the Flower.h header file as follows:
     
    #pragma once
    
    public ref class CFlower
    {
    private:
        int    _tp;
        int    _clr;
        int    _arg;
        bool   _mx;
        double _price;
    
    public:
        property int Type
        {
            int get() { return _tp; }
            void set(int tp) { _tp = tp; }
        }
    
        property int Color
        {
            int get() { return _clr; }
            void set(int clr) { _clr = clr; }
        }
    
        property int Arrangement
        {
            int get() { return _arg; }
            void set(int arg) { _arg = arg; }
        }
    
        property bool Mixed
        {
    	bool get() { return _mx; }
    	void set(bool mx) { _mx = mx; }
        }
    
        property double UnitPrice
        {
            double get() { return _price; }
            void set(double price) { _price = price; }
        }
    
    public:
        CFlower(void);
        CFlower(int type, int color,
                int argn, bool mx, double price);
        ~CFlower();
    };
  2. Access the Flower.cpp source file and change it as follows:
     
    #include "Flower.h"
    
    CFlower::CFlower(void)
        : _tp(0), _clr(0),
          _arg(0), _mx(false),
          _price(45.95)
    {
    }
    
    CFlower::CFlower(int type, int color,
                     int argn, bool mx,
                     double price)
        : _tp(type),
          _clr(color),
          _arg(argn),
          _mx(mx),
          _price(price)
    {
    }
    
    CFlower::~CFlower()
    {
    }
  3. Save all
 

Previous Copyright © 2006-2007 FunctionX, Inc. Next