Home

Using Variables

 

Techniques of Using Variables

 

References

A reference is a variable name that is a duplicate of an existing variable. It provides a techniques of creating more than one name to designate the same variable. The syntax of creating or declaring a reference is:

DataType &ReferenceName = VariableName;

To declare a reference, type the variable’s name preceded by the same type as the variable it is referring to. Between the data type and the reference name, type the ampersand operator “&”. To specify what variable the reference is addressed to, use the assignment operator “=” followed by the name of the variable. The referred to variable must exist already. You cannot declare a reference as:

int &Mine;

The compiler wants to know what variable you are referring to. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{          
    int Number = 228;
    int &Nbr = Number;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

The ampersand operator between the data type and the reference can assume one of three positions as followed:

int& Nbr;
int & Nbr;
int &Nbr;

As long as the & symbol is between a valid data type and a variable name, the compiler knows that the variable name (in this case Nbr) is a reference.

Once a reference has been initialized, it holds the same value as the variable it is pointing to. You can then display the value of the variable using either of both:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{          
    int Number = 228;
    int & Nbr = Number;

    cout << "Number = " << Number << "\n";
    cout << "Its reference = " << Nbr;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

If you change the value of the variable, the compiler updates the value of the reference so that both variable would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Number = 228;   // Regular variable
    int& Nbr = Number;  // Reference

    cout << "Number = " << Number << "\n";
    cout << "Its reference = " << Nbr << "\n";

    // Changing the value of the original variable
    Number = 4250;
    cout << "\nNumber = " << Number;
    cout << "\nIts reference = " << Nbr << "\n";

    // Modifying the value of the reference
    Nbr = 38570;
    cout << "\nNumber = " << Number;
    cout << "\nIts reference = " << Nbr;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

In the way, you can use either a reference or the variable it is referring to, to request the variable’s value from the user. Here is an example:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double Price;
    double& RefPrice = Price;

    cout << "What's the price? $";
    cin >> Price;
    cout << "Price = $" << Price << "\n";
    cout << "Same as $" << RefPrice << "\n\n";

    cout << "What's the price? $";
    cin >> RefPrice;
    cout << "Price = $" << Price << "\n";
    cout << "Same as $" << RefPrice << "\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
 

The typedef Type Definition

 

Some of the identifiers we have used so far and some others we will learn further with arrays, pointers, and objects can be simplified and reduced to a new one-word identifier. C++ allows you to define a new variable using typedef. Indeed, typedef is not a new or other identifier. It provides a technique of redefining any of the known identifiers or by naming those that are combined.

The formula of using the typedef is:

typedef Identifier NewName;

The typedef word is required to let the compiler know that you are creating a new identifier. The Identifier is any of those we have learned so far. It could be an int, an unsigned int, a char, a double, etc. An example of declaring a typedef is:

typedef int NumberOfStudents;

In this case, NumberOfStudents is just a new name for an int. It can be used as a new identifier exactly as if you were using an int. Here is an example that redefines an int identifier:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    typedef int NumberOfStudents;

    NumberOfStudents Grade1, Grade2;
    cout << "Enter the number of students.\n";
    cout << "Grade 1: ";
    cin >> Grade1;
    cout << "Grade 2: ";
    cin >> Grade2;

    cout << "\nNumber of students:";
    cout << "\n1st Grade: " << Grade1;
    cout << "\n2nd Grade: " << Grade2;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here are examples of creating new identifiers using typedef:

typedef unsigned int uInt;
typedef unsigned char uChar;
typedef unsigned long uLong;
typedef long double lDouble;

The compiler you are using shipped with a lot of data types, some of which are redefined versions of existing C++ data types. Therefore, the identifiers you will be using in C++ Builder come in three sets. The C++ language has its own data types that are integers, floating values, etc. Borland C++ Builder has a list of redefined types in the sysmac.h library. The Microsoft Windows operating systems ships with the Win32 library that has a set of redefined data types. To see its list, in the MSDN library, do a search on Data Types [Win32].

In this book, we will interchangeably use any data type we see fit for the task at hand, without identifying whether it is part of C++, Borland C++ Builder, or Win32. For that reason, from now on, many of our programs will include the VCL library.

Practical Learning Practical Learning: Using the typedef Keyword

  1. To open WordPad, from the Taskbar, click Start -> Programs -> Accessories -> WordPad.
  2. Locate the C:\Program Files\Borland\CBuilder5\Include\Vcl folder.
  3. Double-click sysmac to open that header file.
  4. Scroll down to locate the section with the type definitions.
  5. Close WordPad. If you are asked to save anything, click No.
 

Constants

 

Introduction

 

A constant is a value that does not change. There are various categories of constants you will be using in your programming life: Those that are mathematically defined (such as numbers); those that are defined by, and are part of, the C++ language; those defined by the Microsoft Windows operating system you are using, and those defined by the Borland C++ Builder compiler or libraries. To make their management easier, these constant values have been categorized and defined in particular libraries. Throughout this book, you will be using them.

The algebraic numbers you have been using all the time are constants because they never change. Examples of constant numbers are 12, 0, 1505, or 88146. Therefore, any number you can think of is a constant.

Every letter of the alphabet is a constant and is always the same. Examples of constant letters are d, n, c.

Some characters on your keyboard represent symbols that are neither letters nor digits. These are constants too. Examples are #, &, |, !.

Some values would be constant by default, but their constancy sometimes depends on the programmer. For example, one programmer can define a const PI as 3.14; another programmer can decide that the constant PI would be 3.14159; yet another programmer would use a more precise value. Therefore, you will be defining your own constant values as you see fit for the goal you are trying to achieve.

There are two main techniques you use to display a constant value in C++. To simply display it using the cout operator, you can use its value on the right side of the << symbols. You can also define it first using an appropriate name, and then using that name to display the constant.

Practical Learning Practical Learning: Using Constant Values

 
  1. On the Standard toolbar, click the New button New
  2. On the New Items dialog, click Console Wizard and click OK
  3. On the Console Wizard dialog, make sure that the C++ radio button, the VCL, and the Console Application check boxes are selected:
     
    Console Wizard
  4. Click OK
  5. Change the content of the file as follows:
     
    //---------------------------------------------------------------------------
    #include <vcl.h>
    #include <iostream.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        cout << 28;
        cout << "\nStudent Age: " << 14;
    
        cout << "\n\nPress any key to continue...";
        getchar();
        return 0;
    }
    //---------------------------------------------------------------------------
  6. To test the program, press F9

Creating Custom Constants

 

You can create your own constant that represents anything you want. The safest technique of using a constant is to give a name. This allows you to manage it from one standpoint. For example, if you plan to use a number such as 3.14 that represents PI, you can simply use the constant 3.14. Imagine you want to use 3.14 in various sections of the program. If you decide to change the number from 3.14 to 3.14159 or another value, you would have to find every mention of 3.14; this can be cumbersome and considered bad programming. The alternative is to create a variable and assign it the desired value. That new and defined value is called a constant.

To create a constant, you use the const keyword. The simplest way you can do this is to type the const keyword followed by a name, followed by =, followed by the desired value, and terminated by a semi colon. Here is an example:

const NumberOfDoors = 4;

After creating such a constant, you can display its value using the cout extractor:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    const NumberOfDoors = 4;

    cout << "Number of doors = " << NumberOfDoors;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Number of doors = 4

You can also involve such a constant in an operation as we will learn in the next lesson.

When creating a constant as done above, the compiler assumes that the constant is of type integer. If you initialize it to a value that is not an integer, the compiler would try to convert it into an integer. Consider the following example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    const NumberOfDoors = 125.558;

    cout << "Number of doors = " << NumberOfDoors;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Number of doors = 125

The safest way to initialize a constant is to specify the type of data of that constant. To do this, you enter the data type between the const keyword and the name of the constant. Here is an example:

const double NumberOfValues    = 125.558;
const long double Population   = 258994;
const unsigned short int Alley = 88;

If you already know (and have included) a constant, you can initialize your new constant with it. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    const double NumberOfValues = 125.558;
    const long double Population = 258994;
    const unsigned short int Alley = 88;

    const double Root = NumberOfValues;

    cout << "Constants";
    cout << "\nValues:     " << Root;
    cout << "\nPopulation: " << Population;
    cout << "\nAlley Val:  " << Alley;
    cout << "\nRoot Value: " << NumberOfValues;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Using #define

 

The C language provides a preprocessor used to create macros. A macro is an action you want the compiler to perform for your program. The particularity of macros, or most macros, is that the compiler counts on you to know what you are doing. Many of such macros are created using the #define preprocessor.

Based on this concept of macros, you can create a constant. The formula of creating a constant using the define keyword is:

#define ConstantName ConstantValue

The # symbol and the define keyword are required; they inform the compiler to consider that the following name represents a constant.

The ConstantName represents a valid name for the desired constant; the name follows the same rules we learned for defining names in C++. To distinguish the constant from other names of variables, it is sometimes a good idea to write it in uppercase, although it is perfectly normal to have it in lowercase or any case combination you desire.

The ConstantValue can be a character, an integer, a floating-point value, or an expression. If the constant value is an integer or a floating-point value, you can type it. If the value is a character, include it between single-quotes. If the constant value is a string, include it between double-quotes. The definition of the constant does not end with a semi-colon.

Examples of declaring constants are:

#define AGE 12 // AGE represents the constant integer 12
#define ANSWER ‘y’
#define MAXSTUDENTS 35
#define And "&&"
#define PI 3.14159 // PI represents 3.14159
#define Country = “New Zealand”;

As you can see, there is no precision as to what type of constant you are creating when using #define. The truth is that #define doesn't create a constant. It is simply telling the compiler that the word after #define will be used to represent whatever follows that ConstantName. This means that, in reality, what follows ConstantName can be anything; it can even be an expression. here is an expression:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    #define Add255To1250 255 + 1250

    cout << "Addition: " << Add255To1250;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

In reality, the #define technique was implemented in the C language and C++, as a child of C, simply inherited it from its parent. The #define routine is still supported and you will encounter it in many documents. In fact, you are not necessarily discouraged from using it but the golden rule is to know what you are doing.

Operating System and Compiler Constants

 

Because constants are highly used in mathematics and other scenarios, both the C++ language and the Borland C++ Builder compiler  are equipped with various constants. Although you can create your own constants anytime, you should be aware of these constants and usually use them instead of creating new ones, unless yours are more reliable.

Some of the constants that are part of the C++ language are defined in the _lim.h library. Other constants are defined in various other files such as windows.h, System.hpp, SysUtils.hpp, math.hpp, etc. For example, the minimum value of the short integer is SHRT_MIN; in the same way, the maximum short integer is identified by SHRT_MAX. You can use either of these constants as follows:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    cout << "The minimum short integer is: " << SHRT_MIN << "\n";
    cout << "The maximum short integer is: " << SHRT_MAX << "\n";

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

The integral constants are defined in the _lim.h library.

Practical Learning Practical Learning: Using Compiler Constants

 
  1. To view the list of constant integers, open Windows Explorer.
  2. Display the content of the C:\Program Files\Borland\Cbuilder\Include folder
  3. Double-click the _lim.h file to open it.
    Since you get the last way, I will not provide.
 

Namespaces

 
 

Definition

 

A namespace is a section of code, delimited and referred to using a specific name. A namespace is created to set apart a portion of code with the goal of reducing, otherwise eliminating, confusion. This is done by giving a common name to that portion of code so that, when referring to it, only entities that are part of that section would be referred to.

A namespace is not a variable. It is not a constant. It is not a class. And it is not a file. It is simply a name used to refer to a section of code.
 

Creating a Namespace

 

The syntax of creating a name space is:

namespace Name { Body }

The creation of a namespace starts with the (required) namespace keyword followed by a name that would identify the section of code. The name follows the rules we have been applying to C++ names. A namespace contains a body; this is where the entities that are part of the namespace would be declared or defined. The body of the namespace starts with an opening curly bracket “{” and ends with a closing curly bracket “}”. Here is an example of a simple namespace:

namespace Mine
{
    int a;
}

The entities included in the body of a namespace are referred to as its members.

Using the Scope Access Operator

 

To access a member of a namespace, there are various techniques you can use. The scope access operator “::” used for classes is the same you can use here. To do this, type the name of the namespace, followed by the scope access operator “::”, followed by the member you are want to access. Only the members of a particular namespace are available when using its name. For example, to access the member “a” of the Mine namespace above, you can write:

Mine::a;

Once you have access to a namespace member, you can initialize it or display its value using the cout extractor operator. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace Mine
{
    int a;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    Mine::a = 140;

    cout << "Value of a = " << Mine::a;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Value of a = 140

Press any key to continue...

When creating a namespace, you can add as many members as you see fit. When necessary, you can use the scope access operator to call anyone of them as needed. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    InterestAndDiscount::Principal = 3250;
    InterestAndDiscount::Rate = 14; // %
    InterestAndDiscount::Time = 2;

    cout << "Interest Calculation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
    cout << "\nRate:       " << InterestAndDiscount::Rate << "%";
    cout << "\nTime:       " << InterestAndDiscount::Time << " years";

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

You can also request the values of the members of a namespace from the user. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    cout << "Interest and Discount\n";
    cout << "Principal: $";
    cin >> InterestAndDiscount::Principal;
    cout << "Rate (between 0 and 100): ";
    cin >> InterestAndDiscount::Rate;
    cout << "Time (Nbr of Years): ";
    cin >> InterestAndDiscount::Time;

    cout << "\nInterest Calculation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
    cout << "\nRate:       " << InterestAndDiscount::Rate << "%";
    cout << "\nTime:       " << InterestAndDiscount::Time << " years";

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Interest and Discount
Principal: $12500
Rate (between 0 and 100): 7.25
Time (Nbr of Years): 10

Interest Calculation
Principal: $12500.00
Rate:       7.25%
Time:       10 years

Press any key to continue...

In the same way, you can manipulate the members of a namespace as your application needs. They can be part of a conditional statement or the can be involved in any type of arithmetic operation. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double Interest, Discount;

    cout << "Interest and Discount\n";
    cout << "Principal: $";
    cin >> InterestAndDiscount::Principal;
    cout << "Rate (between 0 and 100): ";
    cin >> InterestAndDiscount::Rate;
    cout << "Time (Nbr of Years): ";
    cin >> InterestAndDiscount::Time;

    Discount = InterestAndDiscount::Rate / 100;
    Interest = InterestAndDiscount::Principal * Discount *
    InterestAndDiscount::Time;

    cout << "\nInterest Calculation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
    cout << "\nRate:       " << InterestAndDiscount::Rate << "%";
    cout << "\nTime:       " << InterestAndDiscount::Time << " years";
    cout << "\nInterest:  $" << Interest;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Interest and Discount
Principal: $2500
Rate (between 0 and 100): 6.25
Time (Nbr of Years): 4

Interest Calculation
Principal: $2500.00
Rate:       6.25%
Time:       4 years
Interest:  $625.00

Press any key to continue...

Practical Learning Practical Learning: Creating a Namespace

 
  1. Create a new C++ Console Application using the Console Wizard.
  2. Save the unit as Main in a new folder called Students1
  3. Save the project as Students
  4. To create a new namespace, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        Students::FirstName = "Laurentine";
        Students::LastName = "Sachs";
        Students::Gender = 'F';
    
        cout << "Student Registration";
        cout << "\nFull Name: "
             << Students::FirstName << " " << Students::LastName;
        cout << "\nGender: " << Students::Gender;
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  5. To test the program, on the main menu, click Run -> Run:
     
    Student Registration
    Full Name: Laurentine Sachs
    Gender: F
    
    Press any key to continue...
  6. After testing the program, return to Bcb
  7. To request the values of the members of a namespace, change the main() function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        cout << "Student Registration\n";
        cout << "First Name: ";
        cin >> Students::FirstName;
        cout << "Last Name: ";
        cin >> Students::LastName;
        cout << "Gender (m=Male/f=Female): ";
        cin >> Students::Gender;
        Students::Gender = toupper(Student::Gender);
    
        cout << "\nStudent Registration";
        cout << "\nFull Name: "
             << Students::FirstName << " " << Students::LastName;
        cout << "\nGender:    " << Students::Gender;
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  8. Test the program and return to Bcb.
  9. To apply a conditional statement to a member of a namespace, change the main() function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        cout << "Student Registration\n";
        cout << "First Name: ";
        cin >> Students::FirstName;
        cout << "Last Name:  ";
        cin >> Students::LastName;
        cout << "Gender (m=Male/f=Female): ";
        cin >> Students::Gender;
        Students::Gender = toupper(Students::Gender);
    
        cout << "\nStudent Registration";
        cout << "\nFull Name: "
             << Students::FirstName << " " << Students::LastName;
        cout << "\nGender:    ";
        if( Students::Gender == 'M' )
            cout << "Male";
        else if( Students::Gender == 'F' )
            cout << "Female";
        else
            cout << "Unspecified...";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  10. Test the program. Here is an example:
     
    Student Registration
    First Name: Leslie
    Last Name:  Epps
    Gender (m=Male/f=Female): d
    
    Student Registration
    Full Name: Leslie Epps
    Gender:    Unspecified...
    
    Press any key to continue...
  11. Return to Bcb
  12. When using the scope access operator “::” to call members of a namespace, each member has to be qualified with the operator. This reduces confusion as to what variable you are referring to and also allows you to use the same name in different parts of a program. For example, in a function, you can have a local variable that holds the same name as a member of a namespace. When calling such a variable, the “::” operator can set apart what variable you are referring to. To demonstrate this, a Gender variable is declared in both a name space and the main() function. The use of the access operator helps to specify which Gender variable is called at one time. To test it, change the main() function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        string Gender; // Local variable bearing the same name as above
    
        cout << "Student Registration\n";
        cout << "First Name: ";
        cin >> Students::FirstName;
        cout << "Last Name:  ";
        cin >> Students::LastName;
        cout << "Gender (m=Male/f=Female): ";
        cin >> Students::Gender;
        Students::Gender = toupper(Students::Gender);
    
        // Testing the value of a member of a namespace
        if( Students::Gender == 'M' )
            Gender = "Male"; // Initializing a local variable
        else if( Students::Gender == 'F' )
            Gender = "Female";
        else
            Gender = "Unspecified...";
    
        cout << "\nStudent Information";
        cout << "\nFull Name: "
             << Students::FirstName << " " << Students::LastName;
        cout << "\nGender:    " << Gender; // Displaying a local variable
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  13. Test the program. Here is an example:
     
    Student Registration
    First Name: Josiane
    Last Name:  Pugnol
    Gender (m=Male/f=Female): f
    
    Student Information
    Full Name: Josiane Pugnol
    Gender:    Female
    
    Press any key to continue...
  14. Return to Bcb

The using Keyword

 

The scope access operator “::”provides a safe mechanism to access the members of a namespace. If the namespace is very large and the application needs constant access, this might be a little redundant. Another technique used to access the members of a namespace involves using two keywords: using and namespace.

To call a namespace, on the section of the program where you need to access the members, type:

using namespace NamespaceName;

Both the using and the namespace keywords are required by the compiler. The NamespaceName represents the name of the namespace whose member(s) you want to access. Using this technique, the above program can be written:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    using namespace InterestAndDiscount;
    double Interest, Discount;

    cout << "Interest and Discount\n";
    cout << "Principal: $";
    cin >> Principal;
    do {
        cout << "Rate (between 0 and 100): ";
        cin >> InterestAndDiscount::Rate;
    } while(Rate < 0 && Rate > 100);
    cout << "Time (Nbr of Years): ";
    cin >> Time;

    Discount = Rate / 100;
    Interest = Principal * Discount * Time;

    cout << "\nInterest Calculation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nPrincipal: $" << Principal;
    cout << "\nRate:       " << Rate << "%";
    cout << "\nTime:       " << Time << " years";
    cout << "\nInterest:  $" << Interest;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Interest and Discount
Principal: $2500
Rate (between 0 and 100): 5.55
Time (Nbr of Years): 6

Interest Calculation
Principal: $2500.00
Rate:       5.55%
Time:       6 years
Interest:  $832.50

Press any key to continue...

In a mixed environment (we are still inside of one function only) where a local variable holds the same name as the member of a namespace that is being accessed with the using namespace routine, you will be sensitive to the calling of the same name variable. When manipulating such a name of a variable that is present locally in the function as well as in the namespace that is being accessed, the compiler will require more precision from you. You will need to specify what name is being called. 

Practical Learning Practical Learning: The using namespace Keywords

 
  1. To use the using and namespace keywords, change the main() function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        using namespace Students;
    
        cout << "Student Registration\n";
        cout << "First Name: ";
        cin >> FirstName;
        cout << "Last Name:  ";
        cin >> LastName;
        cout << "Gender (m=Male/f=Female): ";
        cin >> Gender;
        Gender = toupper(Gender);
    
        cout << "\nStudent Information";
        cout << "\nFull Name: "
             << FirstName << " " << LastName;
        cout << "\nGender:    ";
        if( Gender == 'M' )
            cout << "Male";
        else if( Gender == 'F' )
            cout << "Female";
        else
            cout << "Unspecified...";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Test the program. Here is an example:
     
    Student Registration
    First Name: Gabrielle
    Last Name:  Ledoux
    Gender (m=Male/f=Female): f
    
    Student Information
    Full Name: Gabrielle Ledoux
    Gender:    Female
    
    Press any key to continue...
  3. Return to Bcb
  4. To declare a variable that holds the same name as a member of a namespace, change the main() function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        string Gender;
        using namespace Students;
    
        cout << "Student Registration\n";
        cout << "First Name: ";
        cin >> FirstName;
        cout << "Last Name:  ";
        cin >> LastName;
        cout << "Gender (m=Male/f=Female): ";
        cin >> Gender;
    
        cout << "\nStudent Information";
        cout << "\nFull Name: "
             << FirstName << " " << LastName;
        cout << "\nGender:    " << Gender;
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  5. Test the program. When asked for the Gender, type m or f and press Enter
  6. Return to Bcb and test the program again. This time, for the Gender, type Male or Female and press Enter. Return to Bcb
  7. To simulate a confusing scenario for namespace and local variables, change the main() function as follows (look at the comments):
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        string Gender;
        using namespace Students;
    
        cout << "Student Registration\n";
        cout << "First Name: ";
        cin >> FirstName;
        cout << "Last Name:  ";
        cin >> LastName;
        cout << "Gender (m=Male/f=Female): ";   
        // What variable are you requesting? The local Gender or Student::Gender?
        cin >> Gender;
    
        // What variable is being compared? The local Gender or Student::Gender?
        if( Gender == 'm' || Gender == 'M' )
            Gender = "Male";
        else if( Gender == 'f' || Gender == 'F' )
            Gender = "Female";
        else
            Gender = "Unspecified...";
    
        cout << "\nStudent Information";
        cout << "\nFull Name: " << FirstName << " " << LastName;
        cout << "\nGender:    " << Gender;
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  8. Test the program. It would not compile
     
    The Messages Window
  9. There are many solutions you can use to resolve this issue. The best and safest technique is to use different names; that is, when declaring your variables, use names that are not part of the namespace you are trying to access. The problem is that it is very unrealistic to know all names that are used by C++, by the operating system, and by the Visual Component Library. The other solution is to qualify the member of a namespace whenever you call it. Therefore change the above program as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        string Gender;
        using namespace Students;
    
        cout << "Student Registration\n";
        cout << "First Name: ";
        cin >> FirstName;
        cout << "Last Name:  ";
        cin >> LastName;
        cout << "Gender (m=Male/f=Female): ";   
        // Once again, are we requesting the local Gender or Student::Gender?
        // Because the Gender belongs to the Student Registration, let's
        // request the Student::Gender value
        cin >> Students::Gender;
    
        // Since we requested the Student::Gender and not the local Gender,
        // We will perform the comparison on that value
        if( Students::Gender == 'm' || Students::Gender == 'M' )
            Gender = "Male";
        else if( Students::Gender == 'f' || Students::Gender == 'F' )
            Gender = "Female";
        else
            Gender = "Unspecified...";
    
        cout << "\nStudent Information";
        cout << "\nFull Name: " << FirstName << " " << LastName;
        // We are locally displaying the Gender. Therefore, we will call it
        cout << "\nGender:    " << Gender;
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  10. Test the program and return to Bcb.

Combining Namespaces

 
 

Using Various Namespaces

 

Various namespaces can be part of the same file and the same application. You can create each namespace and specify its own members in its delimiting curly brackets. With various namespaces on the same file or application, you can have the same variables in different namespaces. Here is an example of two namespaces:

//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
}
//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
}
//---------------------------------------------------------------------------

To access the member of a namespace, use the scope access operator appended to its name and call the desired member. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
}
//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    InterestAndDiscount::Principal = 14500; // $
    InterestAndDiscount::Rate = 12.52; // %
    InterestAndDiscount::Time = 2; // Years
    InterestAndDiscount::Discount = InterestAndDiscount::Rate / 100;
    InterestAndDiscount::Interest = InterestAndDiscount::Principal *
    InterestAndDiscount::Discount *
    InterestAndDiscount::Time;

    cout << "Interest Calculation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nPrincipal: " << setw(4) << "$"
         << InterestAndDiscount::Principal
         << "\nRate: " << setw(17) << InterestAndDiscount::Rate << "%"
         << "\nDiscount: " << setw(9) << "$"
         << InterestAndDiscount::Discount
         << "\nTime: " << setw(14) << InterestAndDiscount::Time << " years"
         << "\nInterest: " << setw(6) << "$"
         << InterestAndDiscount::Interest;

    BuyAndSell::OriginalPrice = 350; // $
    BuyAndSell::TaxRate = 5.75; // %
    BuyAndSell::Discount = 20; // %

    BuyAndSell::TaxAmount = BuyAndSell::OriginalPrice *
                            BuyAndSell::TaxRate / 100;
    BuyAndSell::DiscountAmount = BuyAndSell::OriginalPrice *
                                 BuyAndSell::Discount / 100;
    BuyAndSell::NetPrice = BuyAndSell::OriginalPrice +
                           BuyAndSell::TaxAmount -
                           BuyAndSell::DiscountAmount;

    cout << "\n\nBuy and Sell - Receipt";
    cout << "\nOriginal Price: " << setw(1) << "$"
         << BuyAndSell::OriginalPrice
         << "\nDiscount: " << setw(8) << "$" << BuyAndSell::DiscountAmount
         << "\nTax Rate: " << setw(13) << BuyAndSell::TaxRate
         << "\nTax Amount: " << setw(6) << "$" << BuyAndSell::TaxAmount
         << "\nNet Price: " << setw(6) << "$" << BuyAndSell::NetPrice;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Using the scope access operator like that, you can perform any operation on any member of one namespace applied to a member of another namespace.

We saw earlier that the using namespace routine allows accessing the members of a namespace. This technique is based on the scope of the routine. After typing it, if the name of a variable appears under a using namespace, the compiler would need to reconcile or identify it; if the name of such a variable is not recognized as part of the namespace that is being accessed, the program would not compile. For example, here is an example that uses two using namespace routines:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
}
//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    using namespace InterestAndDiscount;
    Principal = 14500; // $
    Rate = 12.52; // %
    Time = 2; // Years
    Discount = Rate / 100;
    Interest = Principal * Discount * Time;

    cout << "Interest Calculation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nPrincipal: " << setw(4) << "$" << Principal
         << "\nRate: " << setw(17) << Rate << "%"
         << "\nDiscount: " << setw(9) << "$" << Discount
         << "\nTime: " << setw(14) << Time << " years"
         << "\nInterest: " << setw(6) << "$" << Interest;

    using namespace BuyAndSell;
    OriginalPrice = 350; // $
    TaxRate = 5.75; // %
    Discount = 20; // %

    TaxAmount = OriginalPrice * TaxRate / 100;
    DiscountAmount = OriginalPrice * Discount / 100;
    NetPrice = OriginalPrice + TaxAmount - DiscountAmount;

    cout << "\n\nBuy and Sell - Receipt";
    cout << "\nOriginal Price: " << setw(1) << "$" << OriginalPrice
         << "\nDiscount: " << setw(8) << "$" << DiscountAmount
         << "\nTax Rate: " << setw(13) << TaxRate
         << "\nTax Amount: " << setw(6) << "$" << TaxAmount
         << "\nNet Price: " << setw(6) << "$" << NetPrice;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

The above program would not compile because the compiler does not understand what Discount is being referred to in the second Discount call: is it InterestAndDiscount::Discount or BuyAndSell::Discount?

The Messages Window

If you want to use different namespaces with the using namespace routine, each namespace will have to control its scope. One solution would be to create a “physical” scope for each namespace. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
}
//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    {
        using namespace InterestAndDiscount;
        Principal = 14500; // $
        Rate = 12.52; // %
        Time = 2; // Years
        Discount = Rate / 100;
        Interest = Principal * Discount * Time;

        cout << "Interest Calculation";
        cout << setiosflags(ios::fixed) << setprecision(2);
        cout << "\nPrincipal: " << setw(4) << "$" << Principal
             << "\nRate: " << setw(17) << Rate << "%"
             << "\nDiscount: " << setw(9) << "$" << Discount
             << "\nTime: " << setw(14) << Time << " years"
             << "\nInterest: " << setw(6) << "$" << Interest;
    }

    // The scope of the above namespace has been closed
    // So we don't have to create a new scope for the following namespace
    // Since it is the only namespace now, it can control the rest
    // If there was another namespace that shares a similar variable,
    // we would have to create another scope
    using namespace BuyAndSell;
    OriginalPrice = 350; // $
    TaxRate = 5.75; // %
    Discount = 20; // %

    TaxAmount = OriginalPrice * TaxRate / 100;
    DiscountAmount = OriginalPrice * Discount / 100;
    NetPrice = OriginalPrice + TaxAmount - DiscountAmount;

    cout << "\n\nBuy and Sell - Receipt";
    cout << "\nOriginal Price: " << setw(1) << "$" << OriginalPrice
         << "\nDiscount: " << setw(8) << "$" << DiscountAmount
         << "\nTax Rate: " << setw(13) << TaxRate
         << "\nTax Amount: " << setw(6) << "$" << TaxAmount
         << "\nNet Price: " << setw(6) << "$" << NetPrice;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Before creating a “physical” scope, we saw that the compiler is able to point out what problem occurred at compilation time. Fortunately, the compiler is able to explicitly designate what problem it encountered. In this case there is a conflict in name resolution: two namespaces have a member of the same name.

The solution, which is commonly used, is to qualify the variable that is causing the conflict. You can qualify only the second Discount call because the compiler will associate the first Discount call with the first using namespace. The safest way is to qualify both calls to the Discount variable, as follows:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
}
//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    using namespace InterestAndDiscount;
    Principal = 14500; // $
    Rate = 12.52; // %
    Time = 2; // Years
    InterestAndDiscount::Discount = Rate / 100;
    Interest = Principal * InterestAndDiscount::Discount * Time;

    cout << "Interest Calculation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nPrincipal: " << setw(4) << "$" << Principal
         << "\nRate: " << setw(17) << Rate << "%"
         << "\nDiscount: " << setw(9) << "$" << InterestAndDiscount::Discount
         << "\nTime: " << setw(14) << Time << " years"
         << "\nInterest: " << setw(6) << "$" << Interest;

    // The scope of the above namespace has been closed
    // So we don't have to create a new scope for the following namespace
    // Since it is the only namespace now, it can control the rest
    // If there was another namespace that shares a similar variable,
    // we would have to create another scope
    using namespace BuyAndSell;
    OriginalPrice = 350; // $
    TaxRate = 5.75; // %
    BuyAndSell::Discount = 20; // %

    TaxAmount = OriginalPrice * TaxRate / 100;
    DiscountAmount = OriginalPrice * BuyAndSell::Discount / 100;
    NetPrice = OriginalPrice + TaxAmount - DiscountAmount;

    cout << "\n\nBuy and Sell - Receipt";
    cout << "\nOriginal Price: " << setw(1) << "$" << OriginalPrice
         << "\nDiscount: " << setw(8) << "$" << DiscountAmount
         << "\nTax Rate: " << setw(13) << TaxRate
         << "\nTax Amount: " << setw(6) << "$" << TaxAmount
         << "\nNet Price: " << setw(6) << "$" << NetPrice;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Practical Learning Practical Learning: Using Various Namespaces

 
  1. To use various namespaces, change the file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <conio.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    namespace Students
    {
        string FirstName;
        string LastName;
        char Gender;
    }
    namespace StaffMembers
    {
        string FirstName;
        string LastName;
        char MaritalStatus;
        double Salary;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        using namespace Students;
        using namespace StaffMembers;
    
        cout << "Process Student Registration\n";
        cout << "First Name: "; cin >> Students::FirstName;
        cout << "Last Name:  "; cin >> Students::LastName;
        cout << "Gender (m=Male/f=Female): "; cin >> Gender;
    
    
        cout << "\nEnter information about the employee\n";
        cout << "First Name: "; cin >> StaffMembers::FirstName;
        cout << "Last Name:  "; cin >> StaffMembers::LastName;
        cout << "Married (1=Yes/0=No)? ";
        cin >> MaritalStatus;
        cout << "Hourly Salary: $"; cin >> Salary;
    
        cout << "\n - Student Information -";
        cout << "\nFull Name: " << Students::FirstName
             << " " << Students::LastName;
        cout << "\nGender:    ";
        if( Gender == 'm' || Gender == 'M' )
            cout << "Male\n";
        else if( Gender == 'f' || Gender == 'F' )
            cout << "Female\n";
        else
            cout << "Unspecified...\n";
    
        cout << "\n - Staff Member Information -";
        cout << "\nFull Name:      " << StaffMembers::LastName << ", "
             << StaffMembers::FirstName;
        cout << "\nMarital Status: ";
        if( MaritalStatus == '1' )
            cout << "Married";
        else
            cout << "Not Married";
        cout << "\nHourly Salary: $" << Salary << endl;
    
        cout << "\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Test the application. Here is an example:
     
    Process Student Registration
    First Name: Valentin
    Last Name:  Nguyen
    Gender (m=Male/f=Female): M
    
    Enter information about the employee
    First Name: Laurentine
    Last Name:  Sachs
    Married (1=Yes/0=No)? 6
    Hourly Salary: $15.58
    
     - Student Information -
    Full Name: Valentin Nguyen
    Gender:    Male
    
     - Staff Member Information -
    Full Name:      Sachs, Laurentine
    Marital Status: Not Married
    Hourly Salary: $15.58
    
    Press any key to continue...
  3. Return to Bcb

Nesting Namespaces

 

Nesting a namespace is the ability to include a namespace inside (as part of the body) of another namespace. To do this, create the intended namespace as a member of the parent namespace. The nested namespace should have its own name and its own body. Here is an example:

//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
    namespace ItemID
    {
        long ItemNumber;
        string Manufacturer;
        string ItemCategory;
    }
}
//---------------------------------------------------------------------------

To access a member of a nested namespace, first call its parent, type the :: operator, type the name of the nested namespace, followed by the :: operator, then type the name of the variable you are trying to access. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
    namespace ItemID
    {
        long ItemNumber;
        string Manufacturer;
        string ItemCategory;
    }
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    BuyAndSell::OriginalPrice = 34.95;
    BuyAndSell::TaxRate = 7.55;
    BuyAndSell::Discount = 5;
    BuyAndSell::ItemID::ItemNumber = 641238;
    BuyAndSell::ItemID::Manufacturer = "Haring Clothing, Inc.";
    BuyAndSell::ItemID::ItemCategory = "Men's Apparel";

    BuyAndSell::TaxAmount = BuyAndSell::OriginalPrice *
    BuyAndSell::TaxRate / 100;
    BuyAndSell::DiscountAmount = BuyAndSell::OriginalPrice *
    BuyAndSell::Discount / 100;
    BuyAndSell::NetPrice = BuyAndSell::OriginalPrice +
    BuyAndSell::TaxAmount -
    BuyAndSell::DiscountAmount;

    cout << "Buy and Sell - Receipt";
    cout << "\nItem Nunmber: " << BuyAndSell::ItemID::ItemNumber;
    cout << "\nManufacturer: " << BuyAndSell::ItemID::Manufacturer;
    cout << "\nItem Category: " << BuyAndSell::ItemID::ItemCategory;
    cout << "\nOriginal Price: $" << BuyAndSell::OriginalPrice;
    cout << "\nDiscount: $" << BuyAndSell::DiscountAmount;
    cout << "\nTax Rate: " << BuyAndSell::TaxRate;
    cout << "\nTax Amount $" << BuyAndSell::TaxAmount;
    cout << "\nNet Price: $" << BuyAndSell::NetPrice;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Following the same logic, you can have as many namespaces and many nested namespaces in your application as you desire. If you nest a namespace, you can use as many :: operators to qualify each member of the nested namespace you want. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
    namespace ItemIdentifier
    {
        long ItemNumber;
        string DateAcquired;
        namespace ItemType
        {
            int ItemCategory;
            string Manufacturer;
            string Model;
        }
    }
}
//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
    namespace ItemID
    {
        long ItemNumber;
        string Manufacturer;
        string ItemCategory;
    }
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    InterestAndDiscount::Principal = 18450; // $
    InterestAndDiscount::Rate = 14.75; // %
    InterestAndDiscount::Time = 4; // Years
    InterestAndDiscount::Discount = InterestAndDiscount::Rate / 100;
    InterestAndDiscount::Interest = InterestAndDiscount::Principal *
                                    InterestAndDiscount::Discount *
                                    InterestAndDiscount::Time;
    InterestAndDiscount::ItemIdentifier::ItemNumber = 787343;
    InterestAndDiscount::ItemIdentifier::DateAcquired = "10/5/2000";
    InterestAndDiscount::ItemIdentifier::ItemType::ItemCategory = 1;
    InterestAndDiscount::ItemIdentifier::ItemType::Manufacturer = "Honda";
    InterestAndDiscount::ItemIdentifier::ItemType::Model = "Accord";

    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "Processing Item";
    cout << "\nStore Number: " << setw(7)
         << InterestAndDiscount::ItemIdentifier::ItemNumber;
    cout << "\nDate Acquired: " << setw(4)
         << InterestAndDiscount::ItemIdentifier::DateAcquired;
    cout << "\nCategory: " << setw(6)
         << InterestAndDiscount::ItemIdentifier::ItemType::ItemCategory;
    cout << "\nManufacturer: " << setw(6)
         << InterestAndDiscount::ItemIdentifier::ItemType::Manufacturer;
    cout << "\nModel: " << setw(14)
         << InterestAndDiscount::ItemIdentifier::ItemType::Model;
    cout << "\nPrincipal: " << setw(4) << "$"
         << InterestAndDiscount::Principal;
    cout << "\nRate: " << setw(17)
         << InterestAndDiscount::Rate << "%";
    cout << "\nDiscount: " << setw(9) << "$"
         << InterestAndDiscount::Discount;
    cout << "\nTime: " << setw(10)
         << InterestAndDiscount::Time << " years";
    cout << "\nInterest: " << setw(5) << "$"
         << InterestAndDiscount::Interest;

    BuyAndSell::OriginalPrice = 34.95;
    BuyAndSell::TaxRate = 7.55;
    BuyAndSell::Discount = 5;
    BuyAndSell::ItemID::ItemNumber = 641238;
    BuyAndSell::ItemID::Manufacturer = "Haring Clothing, Inc.";
    BuyAndSell::ItemID::ItemCategory = "Men's Apparel";

    BuyAndSell::TaxAmount = BuyAndSell::OriginalPrice *
    BuyAndSell::TaxRate / 100;
    BuyAndSell::DiscountAmount = BuyAndSell::OriginalPrice *
    BuyAndSell::Discount / 100;
    BuyAndSell::NetPrice = BuyAndSell::OriginalPrice +
    BuyAndSell::TaxAmount -
    BuyAndSell::DiscountAmount;

    cout << "\n\nBuy and Sell - Receipt";
    cout << "\nItem Number: " << setw(8)
         << BuyAndSell::ItemID::ItemNumber;
    cout << "\nManufacturer: " << setw(14)
         << BuyAndSell::ItemID::Manufacturer;
    cout << "\nItem Category: " << setw(10)
         << BuyAndSell::ItemID::ItemCategory;
    cout << "\nOriginal Price: " << setw(1) << "$"
         << BuyAndSell::OriginalPrice;
    cout << "\nDiscount: " << setw(8) << "$"
         << BuyAndSell::DiscountAmount;
    cout << "\nTax Rate: " << setw(12) << BuyAndSell::TaxRate;
    cout << "\nTax Amount " << setw(7)
         << "$" << BuyAndSell::TaxAmount;
    cout << "\nNet Price: " << setw(6)
         << "$" << BuyAndSell::NetPrice;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Processing Item
Store Number:  787343
Date Acquired: 10/5/2000
Category:      1
Manufacturer:  Honda
Model:         Accord
Principal:    $18450.00
Rate:             14.75%
Discount:         $0.15
Time:          4 years
Interest:     $10885.50

Buy and Sell - Receipt
Item Number:   641238
Manufacturer: Haring Clothing, Inc.
Item Category: Men's Apparel
Original Price: $34.95
Discount:        $1.75
Tax Rate:         7.55
Tax Amount       $2.64
Net Price:      $35.84

Press any key to continue...

You can also use the using namespace routine by qualifying each member inside the using namespace that “needs” its parent:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
    namespace ItemIdentifier
    {
        long ItemNumber;
        string DateAcquired;
        namespace ItemType
        {
            int ItemCategory;
            string Manufacturer;
            string Model;
        }
    }
}
//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
    namespace ItemID
    {
        long ItemNumber;
        string Manufacturer;
        string ItemCategory;
    }
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    using namespace InterestAndDiscount;
    Principal = 18450; // $
    Rate = 14.75; // %
    Time = 4; // Years
    Discount = Rate / 100;
    Interest = Principal * Discount * Time;
    ItemIdentifier::ItemNumber = 787343;
    ItemIdentifier::DateAcquired = "10/5/2000";
    ItemIdentifier::ItemType::ItemCategory = 1;
    ItemIdentifier::ItemType::Manufacturer = "Honda";
    ItemIdentifier::ItemType::Model = "Accord";

    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "Processing Item";
    cout << "\nStore Number: " << setw(7)
         << ItemIdentifier::ItemNumber;
    cout << "\nDate Acquired: " << setw(4)
         << ItemIdentifier::DateAcquired;
    cout << "\nCategory: " << setw(6)
         << ItemIdentifier::ItemType::ItemCategory;
    cout << "\nManufacturer: " << setw(6)
         << ItemIdentifier::ItemType::Manufacturer;
    cout << "\nModel: " << setw(14)
         << ItemIdentifier::ItemType::Model;
    cout << "\nPrincipal: " << setw(4) << "$" << Principal;
    cout << "\nRate: " << setw(17) << Rate << "%";
    cout << "\nDiscount: " << setw(9) << "$"
         << InterestAndDiscount::Discount;
    cout << "\nTime: " << setw(10) << Time << " years";
    cout << "\nInterest: " << setw(5) << "$" << Interest;

    using namespace BuyAndSell;
    OriginalPrice = 34.95;
    TaxRate = 7.55;
    BuyAndSell::Discount = 5;
    ItemID::ItemNumber = 641238;
    ItemID::Manufacturer = "Haring Clothing, Inc.";
    ItemID::ItemCategory = "Men's Apparel";

    TaxAmount = OriginalPrice * TaxRate / 100;
    DiscountAmount = OriginalPrice * BuyAndSell::Discount / 100;
    NetPrice = OriginalPrice + TaxAmount - DiscountAmount;

    cout << "\n\nBuy and Sell - Receipt";
    cout << "\nItem Nunmber: " << setw(8) << ItemID::ItemNumber;
    cout << "\nManufacturer: " << setw(14) << ItemID::Manufacturer;
    cout << "\nItem Category: " << setw(10) << ItemID::ItemCategory;
    cout << "\nOriginal Price: " << setw(1) << "$" << OriginalPrice;
    cout << "\nDiscount: " << setw(8) << "$" << DiscountAmount;
    cout << "\nTax Rate: " << setw(12) << TaxRate;
    cout << "\nTax Amount " << setw(7) << "$" << TaxAmount;
    cout << "\nNet Price: " << setw(6) << "$" << NetPrice;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Otherwise, you can create a using namespace for each namespace and make sure that each one of them controls its scope. As long as you are using the scope access operator to identify the variable that is being accessed inside of a using namespace, you can call the member of any namespace in any scope, provided you qualify it.

When a namespace is nested, a first using namespace can be used to nvoque the parent namespace. You can use a scope access operator “::” with a using namespace to further refine the members of a sub-namespace as follows:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    int Time;
    double Interest;
    double Discount;
    namespace ItemIdentifier
    {
        long ItemNumber;
        string DateAcquired;
        namespace ItemType
        {
            int ItemCategory;
            string Manufacturer;
            string Model;
        }
    }
}
//---------------------------------------------------------------------------
namespace BuyAndSell
{
    double OriginalPrice;
    double TaxRate;
    double TaxAmount;
    double Discount;
    double DiscountAmount;
    double NetPrice;
    namespace ItemID
    {
        long ItemNumber;
        string Manufacturer;
        string ItemCategory;
    }
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    using namespace InterestAndDiscount;
    Principal = 18450; // $
    Rate = 14.75; // %
    Time = 4; // Years
    Discount = Rate / 100;
    Interest = Principal * Discount * Time;

    using namespace InterestAndDiscount::ItemIdentifier;
    ItemNumber = 787343;
    DateAcquired = "10/5/2000";
    ItemType::ItemCategory = 1;
    ItemType::Manufacturer = "Honda";
    ItemType::Model = "Accord";

    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "Processing Item";
    cout << "\nStore Number: " << setw(7)
         << ItemNumber;
    cout << "\nDate Acquired: " << setw(4)
         << DateAcquired;
    cout << "\nCategory: " << setw(6)
         << ItemType::ItemCategory;
    cout << "\nManufacturer: " << setw(6)
         << ItemType::Manufacturer;
    cout << "\nModel: " << setw(14)
         << ItemType::Model;
    cout << "\nPrincipal: " << setw(4) << "$" << Principal;
    cout << "\nRate: " << setw(17) << Rate << "%";
    cout << "\nDiscount: " << setw(9) << "$"
         << InterestAndDiscount::Discount;
    cout << "\nTime: " << setw(10) << Time << " years";
    cout << "\nInterest: " << setw(5) << "$" << Interest;

    using namespace BuyAndSell;
    OriginalPrice = 34.95;
    TaxRate = 7.55;
    BuyAndSell::Discount = 5;
    ItemID::ItemNumber = 641238;
    ItemID::Manufacturer = "Haring Clothing, Inc.";
    ItemID::ItemCategory = "Men's Apparel";

    TaxAmount = OriginalPrice * TaxRate / 100;
    DiscountAmount = OriginalPrice * BuyAndSell::Discount / 100;
    NetPrice = OriginalPrice + TaxAmount - DiscountAmount;

    cout << "\n\nBuy and Sell - Receipt";
    cout << "\nItem Nunmber:   " << setw(8) << ItemID::ItemNumber;
    cout << "\nManufacturer:   " << setw(14) << ItemID::Manufacturer;
    cout << "\nItem Category:  " << setw(10) << ItemID::ItemCategory;
    cout << "\nOriginal Price: " << setw(1) << "$" << OriginalPrice;
    cout << "\nDiscount:  " << setw(8) << "$" << DiscountAmount;
    cout << "\nTax Rate:  " << setw(12) << TaxRate;
    cout << "\nTax Amount " << setw(7) << "$" << TaxAmount;
    cout << "\nNet Price: " << setw(6) << "$" << NetPrice;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//--------------------------------------------------------------------------- 
 

Built-In Namespaces

 
 

The std Namespace

 

The C++ Standard provides a namespace called std. The std namespace includes a series of libraries that you will routinely and regularly use in your programs. In the implementation of the Borland C++ Builder compiler, the std namespace contains almost all possible libraries you will need when creating your console applications.

The following libraries are part of the std namespace:

algorithm iomanip list ostream streambuf
bitset ios locale queue string
complex iosfwd map set typeinfo
deque iostream memory sstream utility
exception istream new stack valarray
fstream iterator numeric stdexcept vector
functional limits      

The following additional libraries can be used to include C header files into a C++ program:

cassert cios646 csetjmp cstdio ctime cctype
climits csignal cstdlib cwchar cerrno clocale
cstdarg cstring cwctype cfloat cmath cstddef

Therefore, whenever you need to use a library that is part of the std namespace, instead of typing a library with its file extension, as in iostream.h, you can just type the name of the library as in iostream. Then, on the second line, type using namespace std;. As an example, instead of typing

#include <iostream.h>

You can type:

#include <iostream>
using namespace std;

Because this second technique is conform with the C++ Standard, we will use it whenever we need one of its libraries.

Built-In Namespaces

 

The Borland C++ Builder compiler is equipped with many namespaces. In fact, unlike most other compilers, (almost) everything in C++ Builder is included in a a certain namespace. most of the time, you will not be concerned with this fact but some of the classes you will need when doing graphical programming require explicit call to a namespace.

 

 

Previous Copyright © 2005-2012, FunctionX, Inc. Next