Home

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 eliminate, 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.

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.

Accessing a namespace

 

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>
#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...";
    getchar();
    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...";
    getchar();
    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...";
    getchar();
    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 <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;
    do {
        cout << "Rate (between 0 and 100): ";
        cin >> InterestAndDiscount::Rate;
    } while(InterestAndDiscount::Rate < 0 &&
    InterestAndDiscount::Rate > 100);
    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...";
    getchar();
    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...
 

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 Namespace1
  3. Save the project as Names
  4. To create a new namespace, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.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...";
        getchar();
        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>
    #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...";
        getchar();
        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>
    #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...";
        getchar();
        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>
    #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...";
        getchar();
        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.

using the 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>
#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...";
    getchar();
    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. 

The using namespace Keywords

  1. To use the using and namespace keywords, change the main() function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.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...";
        getchar();
        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>
    #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...";
        getchar();
        getchar();
        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>
    #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...";
        getchar();
        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>
    #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...";
        getchar();
        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>
#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...";
    getchar();
    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...";
    getchar();
    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...";
    getchar();
    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 associtate 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...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------
 

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>
#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...";
    getchar();
    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 Nunmber: " << 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...";
    getchar();
    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 Nunmber:   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>
#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...";
    getchar();
    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 invoque 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...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------
 

Namespaces and Functions

 

Functions Local Definition

Like a variable, a function can be part of a namespace. Such a function belongs to the namespace and enjoys all the advantages of the members of a namespace. To declare a function in a namespace, type its return type, followed by a name, followed by the argument(s) if any inside of parentheses. Here is an example:

//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    double Time;
    double CalcInterest();
    double CalcMaturityValue();
}
//---------------------------------------------------------------------------

A member function of a namespace is accessed following the same rules we applied to member variables, using the scope access operator.

There are two main ways you can implement a member function. In the body of the namespace, which is a local implementation, delimit the body of the function with an opening curly bracket “{“ and a closing curly bracket “}”. A function that is a member of a namespace has complete access to the member variables of the same namespace. Therefore, you do not have to pass the member variables as arguments to the member functions. It is also a good idea to make your functions fastcall to accelerate the execution of the program. Here is an example:

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

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

#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
    double Principal;
    double Rate;
    double Time;
    double __fastcall CalcInterest()
    {
        double RateValue = Rate / 100;
        return Principal * RateValue * Time;
    }
    double __fastcall CalcMaturityValue()
    {
        return Principal + CalcInterest();
    }
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    InterestAndDiscount::Principal = 6500; // $
    InterestAndDiscount::Rate = 14.00;// %
    InterestAndDiscount::Time = 2; // Years

    cout << "Interest on a loan";
    cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
    cout << "\nRate:       " << InterestAndDiscount::Rate << "%";
    cout << "\nTime:       " << InterestAndDiscount::Time << " years";
    cout << "\nInterest:  $" << InterestAndDiscount::CalcInterest();
    cout << "\nMaturity Value: $" << InterestAndDiscount::CalcMaturityValue();

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

This would produce:

Interest on a loan
Principal: $6500
Rate:       14%
Time:       2 years
Interest:  $1820
Maturity Value: $8320

Press any key to continue...

If a nested namespace has its own functions, you can also implement them in the body of the nested namespace. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
	double Principal;
	double Rate;
	double Time;
	double __fastcall Interest()
	{
		return Principal * Rate * Time;
	}
	double __fastcall MaturityValue()
	{
		return Principal + Interest();
	}
	namespace Discounter
	{
		double Maturity;
		double DiscountRate;
		double TermOfDiscount;
		double __fastcall Discount()
		{
			return Maturity * DiscountRate * TermOfDiscount;
		}
	}
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	InterestAndDiscount::Principal = 6500;
	InterestAndDiscount::Rate = 0.14;
	InterestAndDiscount::Time = 2;
	
	cout << "Interest Calculation";
	cout << "\nPrincipal: $" << InterestAndDiscount::Principal;
	cout << "\nRate: " << InterestAndDiscount::Rate;
	cout << "\nTime: " << InterestAndDiscount::Time << " years";
	cout << "\nInterest: $" << InterestAndDiscount::Interest();
	
	cout << "\nPress any key to continue...";
	getchar();
	return 0;
}
//---------------------------------------------------------------------------

After locally implementing the member functions of a nested namespace, you can access its members and display their value in the main() function.

With the using namespace routine, you can improve the access to the members of a namespace as follows:

//---------------------------------------------------------------------------
#include <iomanip.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
	. . .
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	using namespace InterestAndDiscount;
	
	Principal = 12450; // $
	Rate = 12.75;// %
	Time = 4; // Years

	cout << "Interest on a loan";
	cout << "\nPrincipal: $" << Principal;
	cout << "\nRate: " << Rate << "%";
	cout << "\nTime: " << Time << " years";
	cout << "\nInterest: $" << CalcInterest();
	cout << "\nMaturity Value: $" << CalcMaturityValue();

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

Global Definitions

To implement a member function outside the body of a namespace, type the return value, followed by the name of the namespace, followed by the scope access operator “::”. Here is an example:

//---------------------------------------------------------------------------
#include <iomanip.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
	double Principal;
	double Rate;
	double Time;
	double __fastcall CalcInterest();
	double __fastcall CalcMaturityValue();
}
//---------------------------------------------------------------------------
double __fastcall InterestAndDiscount::CalcInterest()
{
	double RateValue = Rate / 100;
	return Principal * RateValue * Time;
}
//---------------------------------------------------------------------------
double __fastcall InterestAndDiscount::CalcMaturityValue()
{
	return Principal + CalcInterest();
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	using namespace InterestAndDiscount;
	Principal = 4200; // $
	Rate = 7.25;// %
	Time = 5; // Years

	cout << "Interest on a loan";
	cout << "\nPrincipal: $" << Principal;
	cout << "\nRate: " << Rate << "%";
	cout << "\nTime: " << Time << " years";
	cout << "\nInterest: $" << CalcInterest();
	cout << "\nMaturity Value: $" << CalcMaturityValue();

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

To implement the member functions of a nested namespace outside of the parent namespace, you must qualify each member function to specify the function (or the variable) you are calling. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
	double Principal;
	double Rate;
	double Time;
	double __fastcall CalcInterest();
	double __fastcall CalcMaturityValue();
	namespace Discounter
	{
		double Maturity;
		double DiscountRate;
		double TermOfDiscount;
		double __fastcall Discount();
	}
}
//---------------------------------------------------------------------------
double __fastcall InterestAndDiscount::CalcInterest()
{
	return Principal * Rate * Time;
}
//---------------------------------------------------------------------------
double __fastcall InterestAndDiscount::CalcMaturityValue()
{
	return Principal + Interest();
}
//---------------------------------------------------------------------------
double __fastcall InterestAndDiscount::Discounter::Discount()
{
	return Maturity * DiscountRate * TermOfDiscount;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	using namespace InterestAndDiscount;
	
	Principal = 120000;
	Rate = 0.175; // = 17.50 / 100
	Time = 0.328; // = 120 / 365
	
	cout << "Interest Calculation";
	cout << "\nPrincipal: $" << Principal;
	cout << "\nRate:       " << Rate;
	cout << "\nTime:       " << Time << " years";
	cout << "\nInterest:  $" << Interest() << "\n";
	
	Discounter::Maturity = 7500;
	Discounter::DiscountRate = 0.155;// = 18.50 / 100;
	Discounter::TermOfDiscount = 0.25;//90 days = 90 / 360;
	
	cout << "\nDiscount Calculator";
	cout << "\nLoan:     $" << Discounter::Maturity;
	cout << "\nDisc Rate: " << Discounter::DiscountRate;
	cout << "\nTerms:     " << Discounter::TermOfDiscount;
	cout << "\nDiscount: $" << Discounter::Discount() << "\n";
	
	cout << "\nPress any key to continue...";
	getchar();
	return 0;
}
//---------------------------------------------------------------------------
 

Namespaces and External Functions

The member variables of a namespace are variables like any of those we have used so far. They can request their values from an outside function. Here is an example:

//---------------------------------------------------------------------------
#include <iomanip.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
	. . .
}
//---------------------------------------------------------------------------
	. . .
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	using namespace InterestAndDiscount;
		
	double __fastcall GetThePrincipal();

	cout << "Loan Processing";
	cout << "\nEnter the following values\n";
	Principal = GetThePrincipal();

	do {
		cout << "Rate (between 0 and 100): ";
		cin >> Rate;
	} while(Rate < 0 || Rate > 100);

	cout << "Time (Nbr of Years): ";
	cin >> Time;

	cout << "\nInterest on a loan";
	cout << "\nPrincipal: $" << Principal;
	cout << "\nRate: " << Rate << "%";
	cout << "\nTime: " << Time << " years";
	cout << "\nInterest: $" << CalcInterest();
	cout << "\nMaturity Value: $" << CalcMaturityValue();

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

	cout << "Principal: $";
	cin >> P;

	while( P < 0 )
	{
		cout << "Enter a positive number: $";
		cin >> P;
	}

	return P;
}
//---------------------------------------------------------------------------

The member of a namespace can also be passed as argument to a function. When passing the argument, if the usng namespace routine has been entered, you can pass the argument like any other. Otherwise, you can qualify the namespace member with the :: operator. In the following example, one member of a namespace is passed by its name only because of the previous using namespace. The other members are passed by being qualified, which is for demonstration purposes only:

//---------------------------------------------------------------------------
#include <iomanip.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
namespace InterestAndDiscount
{
    . . .
}
//---------------------------------------------------------------------------
    . . .
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    using namespace InterestAndDiscount;

    void __fastcall GetThePrincipal(double& p);
    void __fastcall RateAndTime(double &r, double &t);

    cout << "Loan Processing";
    cout << "\nEnter the following values\n";

    GetThePrincipal(Principal);
    RateAndTime(InterestAndDiscount::Rate, InterestAndDiscount::Time);

    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nInterest on a loan";
    cout << "\nPrincipal: $" << Principal;
    cout << "\nRate: " << Rate << "%";
    cout << setiosflags(ios::fixed) << setprecision(0);
    cout << "\nTime: " << Time << " years";
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << "\nInterest: $" << CalcInterest();
    cout << "\nMaturity Value: $" << CalcMaturityValue();

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall GetThePrincipal(double& P)
{
    cout << "Principal: $";
    cin >> P;

    while( P < 0 )
    {
        cout << "Enter a positive number: $";
        cin >> P;
    }
}
//---------------------------------------------------------------------------
void __fastcall RateAndTime(double &rate, double &time)
{
    do {
        cout << "Rate (between 0 and 100): ";
        cin >> rate;
    } while(rate < 0 || rate > 100);

    do {
        cout << "Time (Nbr of Years): ";
        cin >> time;
    } while(time <= 0 || time >= 30);
}
//---------------------------------------------------------------------------
 

Namespaces and Classes

 

Creating a class

Like variables and functions, classes can be part of a namespace. To create a class in a namespace, first type the namespace keyword, followed by a name for the namespace, followed by the opening bracket that starts the namespace. In the body of the namespace, start creating the class the same way you would proceed for a regular class. At the end of the class, remember to end the namespace with its closing curly bracket. Here is an example:

//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TCircle
    {
    public:
        __fastcall TCircle(double r = 0.00);
        __fastcall TCricle(const TCircle& c);
        __fastcall ~TCircle();
        void __fastcall setRadius(const double r);
        double __fastcall getRadius() const;
        double __fastcall Diameter() const;
        double __fastcall Circumference() const;
        double __fastcall Area() const;
    private:
        double Radius;
    };
}
//---------------------------------------------------------------------------

To implement a class that is part of a namespace, you can do so in the namespace, which is a local implementation. The function methods in the above class can be defined as follows:

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

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

#pragma argsused
const double PI = 3.14159;
//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TCircle
    {
    public:
        __fastcall TCircle(double r = 0.00)
            : Radius(r)
        {
        }
        __fastcall TCircle(const TCircle& c) : Radius(c.Radius) {}
        __fastcall ~TCircle() {}
        void __fastcall setRadius(const double r)
        {
            Radius = r;
        }
        double __fastcall getRadius() const { return Radius; }
        double __fastcall Diameter() const { return 2 * Radius; }
        double __fastcall Circumference() const
        {
            return 2 * Radius * PI;
        }
        double __fastcall Area() const
        {
            return Radius * Radius * PI;
        }
    private:
        double Radius;
    };
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    FlatShape::TCircle Cirque(15.50);

    cout << "Characteristics of the circle";
    cout << "\nRadius: " << Cirque.getRadius();
    cout << "\nDiameter: " << Cirque.Diameter();
    cout << "\nCircumference: " << Cirque.Circumference();
    cout << "\nTotal Area: " << Cirque.Area();

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

This would produce:

Characteristics of the circle
Radius: 15.5
Diameter: 31
Circumference: 97.3893
Total Area: 754.767

Press any key to continue...

To globally implement the member methods of a class that is part of a namespace, you can qualify each function using the scope access operator like this:

double __fastcall FlatShapes::TCircle::Area()
{
}

The most efficient technique is to start the implementation with the body of the namespace and then define each function normally. The above functions can be implemented outside the namespace as follows:

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

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

#pragma argsused
const double PI = 3.14159;
//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TCircle
    {
    public:
        __fastcall TCircle(double r = 0.00);
        __fastcall TCircle(const TCircle& c);
        __fastcall ~TCircle();
        void __fastcall setRadius(const double r);
        double __fastcall getRadius() const;
        double __fastcall Diameter() const;
        double __fastcall Circumference() const;
        double __fastcall Area() const;
    private:
        double Radius;
    };
}
//---------------------------------------------------------------------------
namespace FlatShapes
{
    __fastcall TCircle::TCircle(double r)
        : Radius(r)
    {
    }
    __fastcall TCircle::TCircle(const TCircle& c)
        : Radius(c.Radius)
    {
    }
    __fastcall TCircle::~TCircle()
    {
    }
    void __fastcall TCircle::setRadius(const double r)
    {
        Radius = r;
    }
    double __fastcall TCircle::getRadius() const
    {
        return Radius;
    }
    double __fastcall TCircle::Diameter() const
    {
        return 2 * Radius;
    }
    double __fastcall TCircle::Circumference() const
    {
        return 2 * Radius * PI;
    }
    double __fastcall TCircle::Area() const
    {
        return Radius * Radius * PI;
    }
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    FlatShapes::TCircle Cirque(15.50);

    cout << "Characteristics of the circle";
    cout << "\nRadius: " << Cirque.getRadius();
    cout << "\nDiameter: " << Cirque.Diameter();
    cout << "\nCircumference: " << Cirque.Circumference();
    cout << "\nTotal Area: " << Cirque.Area();

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

Creating Files

One of the most efficient techniques of managing objects and their implementations consists of putting headers, called interfaces, in their own files and the source files in separate entities. This is also valid for namespaces. In C++, you can create a header file with an extension of .h, then create a source file with an extension of .cpp. If you are not creating a self-contained header file, in C++ Builder, you should create a unit that is made of a header and a source files.

To create a unit, proceed as we learned for a class. On the main menu, click File ª New. From the New property page of the New Items dialog box, click the Unit icon and click OK. Create the header file using the same syntax we used to create the namespaces so far. Here is an example of the namespace above:

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

#ifndef FlatShapesH
#define FlatShapesH
//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TCircle
    {
    public:
        __fastcall TCircle(double r = 0.00);
        __fastcall TCircle(const TCircle& c);
        __fastcall ~TCircle();
        void __fastcall setRadius(const double r);
        double __fastcall getRadius() const;
        double __fastcall Diameter() const;
        double __fastcall Circumference() const;
        double __fastcall Area() const;
    private:
        double Radius;
    };
}
//---------------------------------------------------------------------------
#endif

To implement the methods of a non self-contained class, include them in the body of the namespace in the source file. The above methods can be defined in a source file as follows:

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

#pragma hdrstop

#include "FlatShapes.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
const double PI = 3.14159;
//---------------------------------------------------------------------------
namespace FlatShapes
{
    __fastcall TCircle::TCircle(double r) : Radius(r)
    {
    }
    __fastcall TCircle::TCircle(const TCircle& c) : Radius(c.Radius)
    {
    }
    __fastcall TCircle::~TCircle()
    {
    }
    void __fastcall TCircle::setRadius(const double r)
    {
        Radius = r;
    }
    double __fastcall TCircle::getRadius() const
    {
        return Radius;
    }
    double __fastcall TCircle::Diameter() const
    {
        return 2 * Radius;
    }
    double __fastcall TCircle::Circumference() const
    {
        return 2 * Radius * PI;
    }
    double __fastcall TCircle::Area() const
    {
        return Radius * Radius * PI;
    }
}//---------------------------------------------------------------------------
 

A Multiple Body Namespace

The creation and/or the declaration of a namespace can be covered in more than one body. This means you can create a namespace with its body in a file, create other namespaces, then start a new body for the same namespace in another section of the same file. All you have to do is to use the same name and define a body for each. In the following header file, the FlatShape namespace is created with two bodies in the same file:

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

#ifndef FlatShapesH
#define FlatShapesH
//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TCircle
    {
    public:
        __fastcall TCircle(double r = 0.00);
        __fastcall TCircle(const TCircle& c);
        __fastcall ~TCircle();
        void __fastcall setRadius(const double r);
        double __fastcall getRadius() const;
        double __fastcall Diameter() const;
        double __fastcall Circumference() const;
        double __fastcall Area() const;
    private:
        double Radius;
    };
}
//---------------------------------------------------------------------------
namespace ShapeCategories
{
    struct TCategories
    {
        int NumberOfSides;
        char SideType;
        string Name;
        void __fastcall setCategories(int n, char s, string m);
        int __fastcall getSides() const;
        string _fastcall getSideType() const;
        string __fastcall getName() const;
    };
}
//---------------------------------------------------------------------------
namespace FlatShape
{
    class TSquare
    {
    public:
        __fastcall TSquare(double s = 0.00);
        __fastcall TSquare(const TSquare& c);
        __fastcall ~TSquare();
        void __fastcall setSide(const double s);
        double __fastcall getSide() const;
        double __fastcall Perimeter() const;
        double __fastcall Area() const;
    private:
        double Side;
    };
}
//---------------------------------------------------------------------------
#endif

You can also create the same namespace in different files. To do this, start each namespace with the same name and the opening curly bracket. In the body, create the class as you see fit. For example, the FlatShapes namespace above was created in a header file named FlatFhapes.h. In addition to, and in, the same project, another file called Surfaces.h was created as followed:

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

#ifndef SurfacesH
#define SurfacesH
//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TRectangle
    {
    public:
        __fastcall TRectangle(double L = 0.00, double H = 0.00);
        __fastcall TRectangle(const TRectangle& r); // Copy Constructor
        __fastcall ~TRectangle(); // Destructor
        void __fastcall setLength(const double L);
        void __fastcall setHeight(const double H);
        double __fastcall getLength() const;
        double __fastcall getHeight() const;
        double __fastcall Perimeter() const;
        double __fastcall Area() const;
    private:
        double Length;
        double Height;
    };
}
//---------------------------------------------------------------------------
#endif

To implement the classes of the namespace, you can use the same body of the namespace for all of them:

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

#pragma hdrstop

#include "FlatShapes.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
const double PI = 3.14159;
//---------------------------------------------------------------------------
namespace FlatShapes
{
    __fastcall TCircle::TCircle(double r) : Radius(r)
    {
    }
    __fastcall TCircle::TCircle(const TCircle& c) : Radius(c.Radius)
    {
    }
    __fastcall TCircle::~TCircle()
    {
    }
    void __fastcall TCircle::setRadius(const double r)
    {
        Radius = r;
    }
    double __fastcall TCircle::getRadius() const
    {
        return Radius;
    }
    double __fastcall TCircle::Diameter() const
    {
        return 2 * Radius;
    }
    double __fastcall TCircle::Circumference() const
    {
        return 2 * Radius * PI;
    }
    double __fastcall TCircle::Area() const
    {
        return Radius * Radius * PI;
    }
    __fastcall TSquare::TSquare(double s) : Side(s)
    {
    }
    __fastcall TSquare::TSquare(const TSquare& c) : Side(c.Side)
    {
    }
    __fastcall TSquare::~TSquare()
    {
    }
    void __fastcall TSquare::setSide(const double s)
    {
        Side = s;
    }
    double __fastcall TSquare::getSide() const
    {
        return Side;
    }
    double __fastcall TSquare::Perimeter() const
    {
        return 4 * Side;
    }
    double __fastcall TSquare::Area() const
    {
        return Side * Side;
    }
}
//---------------------------------------------------------------------------
namespace ShapeCategories
{
    void __fastcall TCategories::setCategories(int n, char s, string m)
    {
        NumberOfSides = n; SideType = s; Name = m;
    }
    int __fastcall TCategories::getSides() const
    {
        return NumberOfSides;
    }
    string _fastcall TCategories::getSideType() const
    {
        if( SideType == 'r' )
            return "Round Line";
        else if( SideType == 'c' )
            return "Straight Lines";
        else
            return "Unknown";
    }
    string __fastcall TCategories::getName() const
    {
        return Name;
    }
}
//---------------------------------------------------------------------------

As done with the header file, you can create different bodies of the same namespace in the same file. Here is an example:

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

#pragma hdrstop

#include "FlatShapes.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
const double PI = 3.14159;
//---------------------------------------------------------------------------
namespace FlatShapes
{
    . . .
}
//---------------------------------------------------------------------------
namespace ShapeCategories
{
    . . .
}
//---------------------------------------------------------------------------
namespace FlatShapes
{
    __fastcall TRectangle::TRectangle(double L, double H)
        : Length(L), Height(H)
    {
    }
    __fastcall TRectangle::TRectangle(const TRectangle& r)
        : Length(r.Length), Height(r.Height) { }
    __fastcall TRectangle::~TRectangle() { }
    void __fastcall TRectangle::setLength(const double L) { Length = L; }
    void __fastcall TRectangle::setHeight(const double H) { Height = H; }
    double __fastcall TRectangle::getLength() const { return Length; }
    double __fastcall TRectangle::getHeight() const { return Height; }
    double __fastcall TRectangle::Perimeter() const
    {
        return 2 * (Length + Height);
    }
    double __fastcall TRectangle:: Area() const
    {
        return Length * Height;
    }
}
//---------------------------------------------------------------------------

You can also implement different parts of the same namespace in different source files. Make sure you start each file with the name of the appropriate namespace:

FlatShapes.h

//---------------------------------------------------------------------------
#ifndef FlatShapesH
#define FlatShapesH
#include <iostream.h>
//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TCircle
    {
        . . .
    };
}
//---------------------------------------------------------------------------
namespace ShapeCategories
{
    struct TCategories
    {
        . . .
    };
}
//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TSquare
    {
        . . .
    };
}
//---------------------------------------------------------------------------
#endif

FlatShape.cpp

//---------------------------------------------------------------------------
#pragma hdrstop
#include "FlatShapes.h"
#include "Surfaces.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
const double PI = 3.14159;
//---------------------------------------------------------------------------
namespace FlatShapes
{
    __fastcall TCircle::TCircle(double r) : Radius(r) { }
    . . .
    double __fastcall TSquare::Area() const { return Side * Side; }
}
//---------------------------------------------------------------------------
namespace ShapeCategories
{
    void __fastcall TCategories::setCategories(int n, char s, string m)
    {
        . . .
    }
}
//---------------------------------------------------------------------------

Surfaces.h

//---------------------------------------------------------------------------
#ifndef SurfacesH
#define SurfacesH
//---------------------------------------------------------------------------
namespace FlatShapes
{
    class TRectangle
    {
        . . .
    };
}
//---------------------------------------------------------------------------
#endif

Surfaces.cpp

//---------------------------------------------------------------------------
#pragma hdrstop
#include "Surfaces.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
namespace FlatShapes
{
    __fastcall TRectangle::TRectangle(double L, double H)
        : Length(L), Height(H)
    {
    }
    __fastcall TRectangle::TRectangle(const TRectangle& r)
        : Length(r.Length), Height(r.Height)
    {
    }
    __fastcall TRectangle::~TRectangle() { }
    void __fastcall TRectangle::setLength(const double L)
    {
        Length = L;
    }
    void __fastcall TRectangle::setHeight(const double H)
    {
        Height = H;
    }
    double __fastcall TRectangle::getLength() const
    {
        return Length;
    }
    double __fastcall TRectangle::getHeight() const
    {
        return Height;
    }
    double __fastcall TRectangle::Perimeter(const double Length,
                                            const double Height)
    {
        return 2 * (Length + Height);
    }
    double __fastcall TRectangle:: Area() const { return Length * Height; }
}
//----------------------------------------------------------------------

Regardless of how many bodies you use to create or implement a namespace, there are two main rules you should observe in order to call a member of a namespace. First, you must include the header of where the class was defined. Second, you can call any member of the same namespace as long as you qualify the class member with the name of the namespace. Here is the main() function that calls different classes of the same namespace while the classes have been created and/or implemented in different bodies:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
#include "FlatShapes.h"
#include "Surfaces.h"
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    ShapeCategories::TCategories Cats;
    FlatShapes::TCircle Cirque;

    Cirque.setRadius(8.72);
    Cats.setCategories(1, 'r', "Circle");

    cout << "Characteristics of this shape ";
    cout << "\nNbr of sides:  " << Cats.getSides();
    cout << "\nSide type:     " << Cats.getSideType();
    cout << "\nShape Name:    " << Cats.getName();
    cout << "\nRadius:        " << Cirque.getRadius();
    cout << "\nDiameter:      " << Cirque.Diameter();
    cout << "\nCircumference: " << Cirque.Circumference();
    cout << "\nTotal Area: " << Cirque.Area();

    FlatShape::TSquare Carre(68.44);

    Cats.setCategories(4, 'c', "Square");

    cout << "\n\nProperties of this shape";
    cout << "\nNbr of sides:  " << Cats.getSides();
    cout << "\nSide type:     " << Cats.getSideType();
    cout << "\nShape Name:    " << Cats.getName();
    cout << "\nSide:          " << Carre.getSide();
    cout << "\nPerimeter:     " << Carre.Perimeter();
    cout << "\nArea:          " << Carre.Area();

    double Length = 35.66, Height = 32.48;
    FlatShape::TRectangle Recto(Length, Height);

    Cats.setCategories(4, 'c', "Rectangle");

    cout << "\n\nProperties of this shape";
    cout << "\nNbr of sides:  " << Cats.getSides();
    cout << "\nSide type:     " << Cats.getSideType();
    cout << "\nShape Name:    " << Cats.getName();
    cout << "\nLength:        " << Recto.getLength();
    cout << "\nHeight:        " << Recto.getHeight();
    cout << "\nPerimeter:     " << Recto.Perimeter(Length, Height);
    cout << "\nArea:          " << Recto.Area(Length, Height);

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

Namespaces and Inheritance

Class inheritance that involves namespaces relies on qualification, like the calling of the members of a namespace. To derive a class from a class member of a namespace, type the name of the namespace, followed by the scope access operator, and followed by the name of the base namespace. Here is an example:

//---------------------------------------------------------------------------
#ifndef VolumesH
#define VolumesH
#include "FlatShapes.h"
//---------------------------------------------------------------------------
namespace Volumes
{
    struct TSphere : public FlatShape::TCircle
    {
        double __fastcall Area() const;
        double __fastcall Volume() const;
    };
}
//---------------------------------------------------------------------------
#endif

To implement the methods of the inherited class, you do not need to qualify but the new namespace. The above class can be implemented as follows:

//---------------------------------------------------------------------------
#pragma hdrstop
#include "Volumes.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
const double PI = 3.14159;
//---------------------------------------------------------------------------
namespace Volumes
{
    double __fastcall TSphere::Area() const
    {
        return 4 * Radius * Radius * PI;
    }
    double __fastcall TSphere::Volume() const
    {
        return 4 * Radius * Radius * Radius * PI / 3;
    }
}
//---------------------------------------------------------------------------

Here is the implementation of the main file:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
#include "Volumes.h"
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    ShapeCategories::TCategories Cats;
    Volumes::TSphere Spherus;

    Spherus.setRadius(25.15);
    Cats.setCategories(1, '0', "Sphere");

    cout << "Characteristics of this shape ";
    cout << "\nNbr of sides:  " << Cats.getSides();
    cout << "\nSide type:     " << Cats.getSideType();
    cout << "\nShape Name:    " << Cats.getName();
    cout << "\nRadius:        " << Spherus.getRadius();
    cout << "\nDiameter:      " << Spherus.Diameter();
    cout << "\nCircumference: " << Spherus.Circumference();
    cout << "\nTotal Area:    " << Spherus.Area();

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

The TSphere structure we inherited appeared simplistic. You can use the same approach to derive a more complete class as your new class requires. For example, you can create a class based on the TCircle class of the FlatShape namespace as follows:

//---------------------------------------------------------------------------
#ifndef VolumesH
#define VolumesH
#include "FlatShape.h"
//---------------------------------------------------------------------------
namespace Volumes
{
    struct TSphere : public FlatShape::TCircle
    {
    double __fastcall Area() const;
    double __fastcall Volume() const;
    };
    class TCylinder : public FlatShape::TCircle
    {
    public:
        __fastcall TCylinder(double R = 0.00, double H = 0.00);
        __fastcall TCylinder(const TCylinder& c);
        __fastcall ~TCylinder();
        void setHeight(const double H);
        void setDimensions(const double R, const double H);
        double getHeight() const;
        double LateralArea() const;
        double TotalArea() const;
        double Volume() const;
    protected:
        double Height;
    };
}
//---------------------------------------------------------------------------
#endif

The implementation of such a file follows the same rules we have learned so far. For example, here is the implementation of the TCylinder class:

//---------------------------------------------------------------------------
#pragma hdrstop
#include "Volumes.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
const double PI = 3.14159;
//---------------------------------------------------------------------------
namespace Volumes
{
    double __fastcall TSphere::Area() const
    {
        return 4 * Radius * Radius * PI;
    }
    double __fastcall TSphere::Volume() const
    {
        return 4 * Radius * Radius * Radius * PI / 3;
    }
    __fastcall TCylinder::TCylinder(double R, double H)
        : FlatShape::TCircle(R), Height(H)
    {
    }
    __fastcall TCylinder::TCylinder(const TCylinder& c)
    {
        Radius = c.Radius; Height = c.Height;
    }
    __fastcall TCylinder::~TCylinder()
    {
    }
    void TCylinder::setHeight(const double H)
    {
        Height = H;
    }
    void TCylinder::setDimensions(const double R, const double H)
    {
        setRadius(R); setHeight(H);
    }
    double TCylinder::getHeight() const
    {
        return Height;
    }
    double TCylinder::LateralArea() const
    {
        return 2 * Radius * PI * Height;
    }
    double TCylinder::TotalArea() const
    {
        double LArea = 2 * Radius * PI * Height;
        double Base2 = 2 * Radius * Radius * PI;

        return LArea + Base2;
    }
    double TCylinder::Volume() const
    {
        return Radius * Radius * PI * Height;
    }
}
//---------------------------------------------------------------------------

 

 

Previous Copyright © 2002 FunctionX Next