Activity 9-3 - Placing a Class in a Namespace



In Activity 9-2, we placed functions in different name spaces and used a function with the same name and same number of parameters to do different things.  Note that function overloading would allow us to use functions of the same name but with a different number of arguments or different argument types to do different things.  In this activity we look into another possibility with namespace where we place a class in a name space.

Creating a Namespace with a class
To place some program in a namespace, simply include the program in the namespace grouping:

#ifndef CLASSNAME_H
#define CLASSNAME_H
#include<iostream>
#include<ALL OTHERS>

namespace classname
{
      class myclass
      {
            ...
            ...
      };

} // end classname

#endif

To make the class defined in this namespace available to your programs, use using directive:

using namespace classname;

To illustrate this let's apply this to a class ID that we used in Activity 1.

#define  ID_H
#ifndef ID_H

#include<iostream>

namespace idclass1
    class ID
    {
        public:
            ID( );
            ID(int, int, int);
            void display();
        private:
            int left;
            int middle;
            int right;
    };
} // end of idclass namespace

#endif

Now we can use this in a program.

// File ID.h
#ifndef ID_H
#define  ID_H

#include<iostream.h>

namespace idclass1
{
    class ID
    {
        public:
            ID( );
            ID(int, int, int);
            void display();
        private:
            int left;
            int middle;
            int right;
    };
} // end of idclass1 namespace

#endif
 

// File ID.cpp
#include<iostream.h>
#include "ID.h"

using namespace idclass1;

ID::ID( )
{
   // use default values
}

ID::ID(int l, int m, int r)
{
     left = l;
     middle = m;
     right = r;
}

void ID::display()
{
     cout << right << "-" << middle << "-" << right << endl;
}

// File main_prog.cpp
// This program is a driver written to demonstrate how we can use
// namespaces

#include<iostream>
#include "ID.h"
using namespace std;

// This part will go to the main program, main_prog.cpp
int main( )
{
    using namespace idclass1;

    ID id1;

    id1 = ID(111, 22, 4444);
    id1.display( );

    return 0;
}

Exercise 9.3
Copy and paste the above three program segments in their corresponding files given at the top of each segment.  Once all files are separated, compile using:
% g++  main_prog.cpp  ID.cpp

This will create an a.out file that you can run to display the result, which is 111-22-4444.

Define a new namespace that includes the loan class. Then, create a program that is similar to ex91.cpp but works with the two namespaces that you have defined here.