Sunday, October 21, 2007

Exception using Map an example

Here i will explain exception handling with map template.


Though i prefer a proper class hiearachy for exception handling . But this one also an interesting one.
I need 4 class to explain tis , we can take few less or more then i take.

one enum type we declare which contains the exception type like SUCCESS ,FAILURE ,LOGINFAILURE etc.
Just define this in a .h file called ExceptionType.h
These are the contentent of this ExceptionType.h file
enum ExceptionType
{
SUCCESS = 0, // apps execution is success
LOGINFAIL = 101, // Login Failed
FAIL, // Failed executing
UNKNOWN // Unknown Exception
};


Now we will discuss one more container class (this will map all the exception which we have defined in exceptionType.h)
example
Let say this container class called EnumString.h
// Local Headers
#include "ExceptionType.h"

using namespace std;

// Class Definition
template < class T >
class EnumString
{
public:
// Default Constructor
EnumString< T >();

// Destructor
~EnumString< T >() {}

// Explicit Constructor
explicit EnumString< T >( const T value );// Get method for retreiving value
const T getValue() const
{
return _value;
}

// Get method for retreiving Name
const string& getName() const
{
return _stringMap[_value];
}

// Class Name retrieval method
static const char* className() { return "EnumString"; }


private:
// Method to Container
static void populate();
// Method to set Unknown Exception value into container
static void setUnknownValue();

// Method to get Unknown Exception value from container
static T getUnknownValue();

T _value; // Enum type value
static map< T, string, less< T > > _stringMap;// Container for Enum types
};

template < class T >
map< T, string, less< T > > EnumString< T >::_stringMap;

// Default Constructor
template '<' class T'>'
EnumString'<'T'>'::EnumString()
{
// Do Nothing
}
template '<'class T'>'
EnumString'<'T'>'::EnumString( const T value ) : _value(value)
{

// Check for container empty
if ( _stringMap.size() == 0 )
{
populate();
}

// Check Exception is present in Container
if ( _stringMap.find(value) == _stringMap.end() )
{
// This can occur if the Exception is not defined in the
// omexcpdefs.h and that is thrown from the application
// For this case set "UnKnown Exception" into Container
// And into the KeyType value
_value = getUnknownValue();
setUnknownValue();
}



} // end of EnumString'<'T'>'::EnumString()






template '<'class T'>'
EnumString'<'T'>'::EnumString( const T value ) : _value(value)
{

// Check for container empty
if ( _stringMap.size() == 0 )
{
populate();
}

// Check Exception is present in Container
if ( _stringMap.find(value) == _stringMap.end() )
{
// This can occur if the Exception is not defined in the
// omexcpdefs.h and that is thrown from the application
// For this case set "UnKnown Exception" into Container
// And into the KeyType value
_value = getUnknownValue();
setUnknownValue();
}


} // end of EnumString'<'T'>'::EnumString()

template '<'class ExceptionType'>'
void EnumString'<'ExceptionType'>'::populate()
{

// Add all the Known exceptions
_stringMap[SUCCESS] = " SUCCESS DONE";
_stringMap[LOGINFAIL] = " LOGIN FAILED";
_stringMap[FAIL] = " EXECUTION FAILED";


} // end of EnumString::populate()



template '<'class ExceptionType'>'
void EnumString'<'ExceptionType'>'::setUnknownValue()
{
// Update Unknown exceptions
_stringMap[UNKNOWN] = " UNKNOWN ERROR";

} // end of EnumString'<'ExceptionType'>'::setUnknownValue()

template '<'class ExceptionType'>'
void EnumString'<'ExceptionType'>'::setUnknownValue()
{
// Update Unknown exceptions
_stringMap[UNKNOWN] = "UNKNOWN ERROR";

} // end of EnumString'<'ExceptionType'>'::setUnknownValue()

Now I have defined the container class , this class actually maped the error and all thye stufs...
Now i will define a class which will have a data member of type this container class. This class i have defined for one more level
of indirection.

lets define the class as MyException. and the file name MyException.h
#ifndef MYEXCEPTION_H
#define MYEXCEPTION_H
#include "EnumString.h"
// Class Definition
template '<'class T'>'
class MyException
{
public:
// Default Constructor
MyException < T >();

// Destructor
~MyException'<'T'>'() {}

// Explicit Constructor
explicit MyException( T err ) : _ExpMap(err){}

private:

protected:
EnumString < T > _ExpMap;
};

// Default constructor
template '<'class T'>'
MyException'<'T''>'::MyException()
{
// Do Nothing
}

#endif /* MYEXCEPTION_H */



Then I will define the application class where i will use this , I mean inherit this MyException class .Just have a look
#ifndef APPEXCEPTION_H
#define APPEXCEPTION_H
#include "ExceptionType.h"
#include "MyException.h"
#include

// Class Definition
class AppException : public MyException
{
public:
// Default Constructor
AppException() {}

// Destructor
~AppException() {}

// Explicit Constructor
explicit AppException( ExceptionType expNum )
: MyException(expNum)
{
}

// Method to get Exception Description
const string& getExpName() const
{
return ( _ExpMap.getName() );
}

// Class Name retrieval method
const char* className() { return "AppException"; }

};

#endif /* APPEXCEPTION_H */


So if i want to through an exception of particular type, Just create the object of this type and through it.
Below the unit test code



#include
#include "MyException.h"
#include "appException.h"

int main()
{

for ( int i=0; i != 4; i++ )
{
try
{
if ( i == 0 )
throw AppException(SUCCESS);

if ( i == 1 )
throw AppException(LOGINFAIL);

if ( i == 2 )
throw AppException(FAIL);

if ( i == 3 )
throw AppException((ExceptionType)300);


}
catch ( AppException &exp )
{
cout << "Caught Exception: "'< <' exp.getExpName() << endl;
}
}
return ( 0 );
}

Wednesday, October 10, 2007

Example of template class with delete the variable in safe mode

Hi,
Today i will the example code of template class where i will show the assignment operator overloading ,deleteting the variable in safe mode.

#if !defined(_ARRAY_H)
#define P11_ARRAY_H

namespace MYARRAY {

template< class T > class CArray
{

public:
CArray() : m_data(0), m_size(0) {};

explicit CArray(size_t const n) : m_data(0), m_size(0)
{
Resize(n);
};

CArray(CArray< T > const &oa) : m_data(0), m_size(0)
{
*this = oa;
};

~CArray()
{
if(m_data) {
memset(m_data,0,m_size*sizeof(T)); // Safe delete.
delete [] m_data;
}
};

CArray< T > &operator =(CArray< T > const &oa)
{
Resize(oa.Size());
for( size_t i=0; i < m_size; i++ )
m_data[i] = oa.m_data[i];
return *this;
}

operator T*() const
{
return m_data;
}

size_t Size() const {
return m_size;
};

T* Data() const {
return m_data;
};

void Resize(size_t const n) {
T *t = new T[n];
memset(t,0,n*sizeof(T));
memcpy(t,"SAHU",4);
if(m_data) {
size_t ncopy = (n < m_size) ? n : m_size;
for(size_t i=0; i memset(m_data,0,m_size*sizeof(T)); // Safe delete.
delete [] m_data;
}
m_data = t;
m_size = n;
};


private:
T* m_data;
size_t m_size;

};

} // namespace MYARRAY

#endif // _ARRAY_H


int main()
{
unsigned long ulDataLen = 4;

CArray < unsigned char > Data(ulDataLen);// this will cal explicit cotr

CArray< unsigned char > Data1(4); // this will cal explicit cotr
Data = Data1;//aiisgnment optr
unsigned char * p = Data.Data();
cout<<"m_data = " << Data.Data();
cout<<"\n";

cout << "size = " << Data.Size();


}

Here you can notice one thing i have used guarding in .h file and namespace . If i don,t use using namespace ....., then when i try to access any of the resource from this CArray class , it will give error. OR alternativelly it must be preceded by MYCARRAY::.....
like we use the do in standard namespace
example std::cout... if we don,t use using namespace std;
Do you need more example , then pls mail me , i will come up with better solution with more this jind of code.
Cheer,
Sahu

Monday, October 8, 2007

Function Object with vector and algorithm (STL)

Hi,
I will show some more example with explanation. This functor is heavyly used in STL where
1) Many STL containers and algorithms require specifying a function to perform their operation.
2) A function that takes one parameter is called a unary function, whereas a function that takes two parameters is called a binary function.
3) STL defines three categories of functions.

1.1) Predicates- Trigger actions and always return true or false
1.2)Comparators-Order elements and always return true or false
1.3)General functions-Arbitrary operations on one or more arguments and often return a numeric value

Now we will discuss an example

#include
#include
#include
using namespace std;
class Greater_Than
{
private:
int limit;
public:
Greater_Than(int a) : limit(a) { }
bool operator()(int value)
{
return value > limit;
}
};

int main()
{
Greater_Than g(350);
vector x;
x.push_back(300);
x.push_back(460);
x.push_back(560);
x.push_back(660);
vector::iterator p;
p = find_if( x.begin(), x.end(), g );
if (p != x.end())
{
cout<< "Found element " << *p << endl;
}
}
Explanation.
The vector X is containing with 300,460,560,660.

when find_if() examines each item say x[j] in the vector x, the Greater_Than function object g will be called using operator() with the vector item

It is called like below.
// formally: g.operator()(x[j])

If it finds value greater than 350 , the very next value will be printed.
Sahu

Function Object is function pointer in C

Yes boss it is same as function pointer
Lets have an example

template "<" class T >
struct ADD
{
T operator()(T n,T n1)
{
return n+n1;
}
};

template "<" class T, class funcObj ">"
void printEval(T val,T val1,funcObj f)
{
cout <<>" ());
printEval(1.4,1.6, ADD "<" float ">" ());
return 0;
}
It is self explanatory. Do you want me to explain.? :)
I have compiled using gcc version 2.96 and redhat 7.1
It is working fine.

What is Function Object and Its Use with Example

What is Function Object in C++ ?
Answer:- It is nothing but something like Function Pointer in "C" .Regarding Function pointer and its use , how to read , how to declare all these i have discussed in my previous article.
Points:
1)It takes the place of function pointers in traditional C programming.
2)It works by overloading operator() which in turn called as Functor in c++.
3) It is used in STL.
4) STL has more generalised ,sophisticated ,robust concept of Function pointer. i.e Function Object. So function pointer is Function object we can say.
Note -: Remember(Important) Ponter to member function in c++ (.*,->*) is not exactly function pointer in C. This is something difrent I will discuss later. It is beyond scope of this discussion.
5)So any object that can be called is a function object or FUNCTOR.
6)C function pointer is just one of the example.
7)In c++ , we can call any object ,provided it is overloaded with operator().
In Summery
1.1) A Function Object, or Functor (the two terms are synonymous)
1.2) any object that can be called as if it is a function.
1.3) To accomplish this , it must defines operator().
Example.
class Greater_Than
{
private:
int limit;
public:

Greater_Than(int a) : limit(a) { }
bool operator()(int value)

{
return value > limit;
}
};

int main()
{
Greater_Than gt_five(5);
if (gt_five(7) )

{
cout<<"7 > 5" <<>
}
else
{
cout<< "7 <= 5" <<>
}
}
Explanation
See gt_five is an object of the class Greater_Than which is constructed with value 5.
Here you just notice the statement if (gt_five(7)) , we hust calling like a function.But it is an object. So here now we understood that an object of the class can be called as if it is a function, for this we just have overload the operator ().
Now when the control encounter the statement if (gt_five(7)) then control goes to operator () which return true or false.
so we get the appropiate out put.

Overloading stream insertion and extraction operators

Hi,

Now we will discuss the operator < <> > overloading. One of the advantages of using the iostream objects is that we can customize it to support our own classes.
We will just remeber few things while overloading the these operaor
Points.
1)An overloaded < <>
using namespace std;
class Base
{
public:
int a;
Base()
{
a = 100;
}
friend ostream& operator <<(ostream &os,const Base &obj);
};

ostream& operator << (ostream& os, Base & bb) {
os << bb.a;
os << '/';
return os;
}

int main()
{
Base bb1;
cout << bb1 << endl;
}