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;
}

Wednesday, September 12, 2007

Example of template linking error

B.H
template '<' class t '>'
class b
{
public:
b() ;
~b() ;

} ;

// B.CPP
#include "B.H"
template '<' class t '>'
b'<' t '>'::b()
{
}
template '<' class t '>'
b'<' t>::~b()
{
}


//MAIN.CPP
#include "B.H"
void main()
{
b '<' int '>' bi ;
b '<'float '>' bf ;
}

When compiling b.cpp, the compiler has both the declarations and the definitions available. At this point the compiler does not need to generate any definitions for template classes, since there are no instantiations. When the compiler compiles main.cpp, there are two instantiations: template class
b '<'int'>' and b'<'float'>'. At this point the compiler has the declarations but no definitions!

If do g++ main.cpp ,error will come
if we write g++ main.cpp b.cpp the result is same.
Solution to this we have allready discussed, pls see in my site itselt template instatiation problem.
Regards,
sahu

Why do we need template?

It is a generic type. Something we relate to void * in C language.
It can take any type values. I mean ,It is easy to define a class like Vecror or List.But it is difficult to use the class with another type, we must replace all type names in the original file with the new type, this is a tedious and an error-prone process .
C++ provides a way to write a generic definition that works with any type --Here the answer is "templates". We use templates only to define classes that we want to work with many data types.

It can be used with classes or functions.

Boss it is also irritating if you are using GCC compiler.It's linker allways expect the template declaration and definition at a time while instatiating .If it does not see then there will be linking error some thing indefined error.



I had faced the same problem in STL some 4 years back. Actually In stl we can not have separate file for declaration and definion . It will have the linking problem.Because while instatiating , compile must see the declaration and definition at a time. . So while instatiating , by including mere .h will give the declarion , not the definition, so the linking problem.
In this case
Solution 1;
If we have 2 separate file i.e .h and .cpp , then while instatiting we should include .cpp instead of .h
Solution 2:
we have to give the definition in .h itself, and while instatiting compiler does not face any problem because it see the both declaration and definition at a time.
Note:- the gcc has implemented the vector,list all thes predefined STL in this way ,if we open any of stl header file we can see these implemetation.
This linking proble generally we don’t face in Solarice, But is a ovious problem for gcc linker

Regards,
Haramohan sahu

What is template instantiation

A C++ template is a framework for defining a set of classes or functions.
The instantiation, creates a particular class or function , by resolving the C++ template with a group of arguments that may be types or values.

Lets have an example.

#include < iostream >
#include < new >
#include < stdexcept >

using namespace std;
template < class T >
class Array
{

T *data; // pointer to heap allocated space
int size; // maximum size
public: T &operator[](int);
Array(int max);

};

template < class T >
Array::Array(int max)
{
size = max;
data = new T[size];

}//end constructor

template < class T >
T& Array::operator[](int index)
{
if (index < 0 || index > = size)
{
throw out_of_range("Array");
}
return data[index];
}//end Array

int main()
{
Array< double > test1(100);
test1[25] = 3.14;
cout< < test2(200);
Array < int > test2(200);
test2[0] = 55;
return 1;

}//end main

Now we will discuss what is instantiation ?
Here ,Array instantiates Array with type int.
This instantiation generates the following class definition:
class Array
{
int *data;
int size;
public:
int &operator[](int);
};

Like that it instatiate for float etc.
So now, we have understood what is instantiation.

Q 2) How to write the methos definition out side the class if it is a template class?

fist write the template type that the class use. Here in our case
template
then in as usual manner like reurn type then class name then method name with signature
Array::Array(int max)
{
size = max; data = new T[size];

}//end constructor



Regards,

sahu

Saturday, August 25, 2007

Why do i need dynamic casting in c++?

Hi ,
We know how to use dynamic casting,but why do i need it ? In which situation ,we will feel about this mechanism....

there are 4 type of casting c++ provides,
1) static_casting
2 const_casting
3) dynamic_casting
4) reinterprit_casting
Here i will discuss about only dynamic one,
whatever i do with dynamic_casting , i can achive the same by C Style casting. So why do i need it...? There are some situation , we should go for dynamic casting.
First i would like to discuss what is dynamic casting.

1) Run-time checked casts in an inheritance hierarchy

2) Finding the beginning of an object

3) Meant for downcasting from a base class to a derived class. This check is done at runtime (as opposed to static casting which can generate the necessary code to do the casting at compile time).

4)Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

5)The base class must be a polymorphic one (by declaring virtual)


example1

class B
{
public:
void show()
{
cout<<"I am in Class B \n"; } /*virtual*/ ~B() { } }; class D : public B { public: void dis() { cout<<"i am in derive class Dis\n"; } }; int main() { B *bPtr = new B; D *dPtr = dynamic_cast(bPtr);//DownCast
// D *dPtr = (D*)(bPtr);
dPtr->show();

}

Here the above programm will show error because source type is not polymorphic

Funtion return array of integer

/*
This example says about the function takes no argument and returns pointer to array
of 3 interger.
*/

#include < iostream >
using namespace std;

int arr[]={11,22,33};

int (*f())[3]
{
cout << arr[1];
return &arr;

}


int main()
{
int(*(*g)())[3]= f;
(**g());
}


Cheer,
Sahu

Friday, August 24, 2007

Some more example of Function pointer.

Example1
Here i just want to write a program which deals with function pointer.
A function taking no argument returning a pointer to function which takes an arument of integer and that returns an integer.
/*
This methos return an int and takes an int
*/

int incr(int x)
{
x++;
cout<< "X val after incremented "<< x <<"\n";
return x;
}
/*
Here f is a function takes no argument ,returns a pointer to function(here say our incr() function) which takes an intger as argument that returns an integer..
Means f returns a function pointer that function pointer points to or hold the address of a function .Now tell me, what kind of fuction.... It can hold function of taking one int and return one int.
*/
int (*f())(int)
{
cout<< "Pls method returned \n";
return plus;
}
int main()
{
cout<<"Inside Main method Func ptr called "<< f()(5) << "\n";
}

cheer,
sahu

Thursday, August 23, 2007

Can i cast char* to a unsigned char* or vice versa ?

No boss , we can not cast char* to a unsigned char* or vice versa.
The reason is , lets first understand static_cast .

Few points about stati cast listed below
1) Only allowed for conversions which the compiler can check
2) we can not use static_cast to a pointer to a non-pointer
3) we can not use static_cast to remove constness(orvolatileness)
4) we can not use static_cast from a virtual base class
5) Static_cast is only for related types.pointer type (remember pointer type, it works fine for general primitive data type i.e int,char ,float)

So here Char* and unsigned char* are two unrelated pointer types. One more thing ,here one of the pointer is void * then we can do it.
Lets have an example,
#include
using namespace std;


void uchar_f1(unsigned char *x)
{
cout<<"uchar_f1 "<< x <<"\n";
}

void char_f1(char *x)
{
cout<<"char_f1"<< x << "\n";
}int main()
{
unsigned char uc[]={ 'A' , 'B' , 'C' };
uc[3]='\0';
char c[]={ '1' , '2' , '3'};
c[3]='\0';
uchar_f1(uc);
char_f1(c);
uchar_f1(static_cast(c));

}

If we write uchar_f1(static_cast(static_cast(c)));

So this will work.
Cheer,
sahu

What is make file and what it does ?

When we develope a project , there may so many files and may be larger files i mean programs.(1) So recompiling large programs takes more time then shorter one.

(2)Suppose i have made chage to one file, so i do't need to recompile other files.

(3) The make program helps us in developing our large programs by keeping track of which portions of the entire program have been changed, compiling only those parts of the program which have changed since the last compile.

all these can be achived by a utility called Make. So we can have set of guide lines i.e rules to be followed for this utility.

Before that i just want some brush up some basics of compiling.

Basically there is 3 steps fo building the program.
step 1
Compiler stage: All C/C++ language code in the .c/cpp file is converted into a lower-level language called Assembly language; making .s files.
step 2
Assembler stage: The assembly language code made by the previous stage is then converted into object code which are fragments of code which the computer understands directly. An object code file ends with .o.
step 3
Linker stage: The final stage in compiling a program involves linking the object code to code libraries which contain certain "built-in" functions, such as printf. This stage produces an executable program, which is named a.out by default

Note : Definition i have taken from net.
Source file assembler linker executable
.................. ..................
.c and .h ------> .s-----> file .o ---> do liniking ----> then finaly we get executable


Sample make file.

Project1: data.o main.o io.o

cc data.o main.o io.o –o project1

Data.o: data.c data.h

cc –c data.c

Main.o: data.h io.h main.c

cc –c main.c

Io.o: io.h io.c

cc –c io.c


we need " makefile " to tell “ make “ what to do.The makefile tells `make' how to compile and link a program.

When `make' recompiles each changed source file must be recompiled.

What are the files afected,if some thing changed ..?
If header changed then

Each C/C++ source file that includes the header file must be recompiled which will produce the
object file corresponding to the source file.
What make does after recompiling the changed files.?
All the object files, whether newly created or saved from previous compilations, are to be linked together to produce the new executable . so we can say linking is done after compilation and then the executable.

Here some of the option i am listing out which is generally used with compiler , i am using gcc.

gcc –c option is used to generate object file( .o file).
gcc –g option is used to debug the executable file
gcc –o is used to give different name for executable instead of a.out.
gcc –DDEBUG=3 is used to Define the macro whose name is DEBUG whose value is 3.

-I option is used to include the path of Header files.
-L option is used to include the path of Library files.

-l( small L) option is used to include the library(.a or .so ).

In Make file , what is -lc, or -lm i don't understand ?
If the library name is libc.a or libc.so , we can include this library using –l option like this –lc where lib and .a/.so by default not required. so we write like this,do,t get confused.

Is there any rules like dependency or target?
Yes
Make files contain dependency rules and construction rules.
What is dependency rule?
It has two parts - a left and right side separated by a :
left side : right side

The left side gives the names of a target(s) (the names of the program or system files) to be built, whilst the right side gives names of files on which the target depends (eg. source files, header files, data files)
Another example.

program1 : main.o test.o command.o
cc -o program1 main.o test.o command.o

main.o : main.c defs.h
cc -c main.c
test.o : test.c defs.h command.h
cc -c kbd.c
command.o : command.c defs.h command.h
cc -c command.c


Here program1 is executable name.

we will use –c is generate .o file.
cc –c main.c will generate main.o

main.o : main.c defs.h => means main.o depends on main.c and defs.h header file.

here will use cc –o program1 to specify executable name as “program1” otherwise by default it will be
a.out



we can use macros in make files.

Make macros :-
SOURCES= main.c f1.c f2.c ( ALL C FILES )
CFLAGS=-g –c ( -g for debugging and –c created .o files )
LFLAGS=-L/usr/lib ( Library PATHNAME )
LIBS=-lm /usr/local/calculation.a ( Library )
There are lots of short cut symbols are ther we can use that
here is the examples.

1) "$< " is shorthand for file name with .c extension

Ex:-
show.o : show.c
cc –c $< Here "$< " show.c

2) $@ is full target name of current target.

Ex:-
edit : show.o
cc –o $@ show.o

Here $@ is edit
example of make file using macros


OBJECTS=main.o f1.o f2.o

LFLAGS=-L/usr/lib -L/home/sahu/cprog

LIBS=/home/sahu/cprog/show.a –lc #Here –lc means libc.a lib and .a are default

CFLAGS=-g -c

INCLUDES=-I/usr/include -I/home/sahu

main.exe : $(OBJECTS)
cc -o main.exe $(LFLAGS) $(OBJECTS) $(LIBS)main.o:main.c
cc $(CFLAGS) $(INCLUDES) main.c

f1.o:f1.c
cc $(CFLAGS) $(INCLUDES) f1.c

f2.o:f2.c
cc $(CFLAGS) $(INCLUDES) $< #Here $<>
clean:
rm -f $(OBJECTS) main.exe

BACKSLASH:-

A backslash( \ ) at the end of the line means that the command is continued on the next line.

Example:-

edit : main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o


MAKEFILE USING IMPLICIT RULES:-

Example:-


OBJECTS=main.o h.o v.o
LFLAGS=-L/usr/lib -L/home/sahu/cprog
LIBS=/home/sahu/cprog/show.a -lc
CFLAGS=-g -c
INCLUDES=-I/usr/include -I/home/sahu
main.exe: $(OBJECTS)
cc -o main.exe $(LFLAGS) $(OBJECTS) $(LIBS)
.c.o:
cc -c $(INCLUDES) $(CFLAGS) $< color="#ff0000">Below Line is called Implicit Rule.
.c.o:
cc -c $(INCLUDES) $(CFLAGS) $<


Meaning of line .c.o: is using .c file we will get .o file.$<>
Now we understand some thing by which we can write a simple Make file.We can name it Makefile or makefile then at the command prompt we can write simply make , if we want to run other then these two name then we have to write make -f makefile name
Next article i will try to write some other macros and little bit bigger make files.
Cheer,
Sahu
hara.sahu@gmail.com






Monday, August 20, 2007

c++ links

http://tinf2.vub.ac.be/~dvermeir/courses/structuur2/notes/explicit-initialization/#step-2

Problem with Implicit conversion

Hi,
there is a serious issue in implicit conversion . what is that ? Some times we get some unintended situation in implicit conversion. Lets have an example which tels this problem.

#include
using namespace std;
class String
{
char * ptr;
public:
/* explicit */ String (int n) //allocate n bytes to the String object
{
ptr = new char[n];
cout<<"int cotr \n"; } String( char *p) // initializes object with char *p { cout<<"char * cotr \n"; ptr= p; } void show() { cout<< s="'a';" s="'a';">.

But this is not what the we have intended. So to prevent such conditions, we can define the class's constructor as explicit.
Just remove comment line /* explicit */
class String
{
//....public:
//....
explicit String (int n); //allocate n bytes
String(const char *p); // initialize sobject with string p
}
Some more example i found from net , Yee Ley .. :)

#include
#include
class T
{
public:
explicit T(int i): data_(i) { std::cerr << "T::T(int)" << std::endl; }
template
operator X() const
{
X x; std::cerr << "T::operator X()" << std::endl; return x;
}
private:
T(const T&) { std::cerr << "T::T(const T&)" << std::endl; }
int data_;
};

int main(int, char**)
{
T t(3); // OK
std::string s1 = t; // OK.
std::string s2(t); // Error: ambiguity.
}

The reason is that std::string has two constructors with a single parameter, taking resp. a const char* or std::string argument.
std::string::string(const char*);
std::string::string(const std::string&*);

Due to the member template, the compiler can convert to both const char* and std::string, with similar "matching quality". Hence the ambiguity.



#include
#include
class T
{
public:
explicit T(int i): data_(i)
{
std::cerr << "T::T(int)" << std::endl;
}
template
operator X() const
{
X x;
std::cerr << "T::operator X()" << std::endl; return x;
}
private:
T(const T&)
{
std::cerr << "T::T(const T&)" << std::endl;
}
int data_;
};
int main(int, char**)
{
T t(3);
std::string s = t;
}

which compiles ok and produces the output T::T(int)
T::operator X()

showing once more that the compiler optimized away the theoretical call to T's copy constructor, in this case by directly putting the result of T::operator std::string(t) in s.






I think ,it is clearlly understood , you can allways reach me
hara.sahu@gmail.com
sahu

Explicit Constructors

What is Explicit Constructors ?
Explicit constructors are simply constructors that cannot take part in an implicit conversion.Then what is implicit conversion , this i could not understand ? ok i will write an example and explain.
Class Base
{
public: Base(int x) { size=x;
}
Base(const Base&)
{
std::cout << "Base::Base(const Base&)" << std::endl;
}
};
void useBase(const Base & aBase)
{
}
int main()
{
//Direct constructor call
Base myObj(123);

// equivalent to bb = Base(123);
Base bb = 123;//implicit conversion

// equivalent to useBase(Base(123) )
useBase(123);//implicit conversion
}

The above program gets compiled and worked fine. But the problem is here the implicit conversion happes.So here we got to know one thing that "For a single argument constructor, C++ by default also defines an implicit conversion."
Is not it? Yes Boss...
Because the implicit conversion involves calling the Base constructor, so enough storage is being allocated for a new Base object,
needless to say the memory reserved for 123 elements contained in the Base. Surely this is not what we intended! ?
Am i correct?
Now i explain the above programm.Befor start explaining the program, i just want to discuss 2 important aspect right now.

1)Explicit syntax

2)Assignment syntax

what are these ?

Explicit syntax
See when we write T t(v) ,here T is type means class name small t is object of that type and v is the argument of some type V which will be initialised by calling the constructor T::T(V v) .

Assignment syntax
T t = v;
For the above statement, the compiler will generate code that is equivalent with the following sequence of steps.
If necessary, i.e. if v(here v is 123 if you take my above example) is not of type T, convert v to a temporary T object
tmp_t. Initialize t using the copy constructor T::T(const T&) with tmp_t
as argument.

In most cases, the compiler may optimize in such way that the effect of the assignment syntax is the same as that of the explicit syntax. This is the case, e.g. if there exists a (non-explicit) constructor T::T(V) (see my the example), where we assume that v has type V.
*************************************************************************
Base bb = 123;

Here the compiler optimized away the call to the copy constructor of Base ,
by directly applying the convertor/constructor Base::Base(int) to bb object.

if write Base bb = 123; it means Base(123) , that is why it is implicitly converted. Same is the case if call useBase(123)
I think it is clearlly understood..... if there is any doubt pls let me know.
Cheer,
sahu
hara.sahu@gmail.com

Saturday, August 18, 2007

How to Avoid Complex Declarations

How to Avoid Complex Declarations
It is very difficult to track and understand the complex declaration of function pointer.
And also not encouraged in standard programming. Because the readability of the code may suffer.
So, what is the panacea ?Simple , just make it as simple a possible .
Use typedefs to reduce the complexity.

Break down a complex declaration into several simpler declarations.
We will take an example .

Every this is easy if there is a simple example …. Am I correct ?

First declare the typedef for the function pointer:

typedef int (*MY_FUNC_PTR)(int);

From now onwards, MY_FUNC_PTR is a function pointer , to a function which takes an integer and returns an integer.

Now, let us define the type, of the pointer to the function pointer array: MY_FUNC_PTR

typedef MY_FUNC_PTR (*PTR_TO_FPTR_ARRAY)[5];

Declaring the FuncRetArrayPtr function is much simpler now.

PTR_TO_FPTR_ARRAY FuncRetArrayPtr ();

Here is the re-written program:

#include
using namespace std;

typedef int (*MY_FUNC_PTR)(int);

typedef MY_FUNC_PTR (*PTR_TO_FPTR_ARRAY)[5];

int Func1(int x)
{
return x+x;
}

int Func2(int y)
{
return y+y;
}

MY_FUNC_PTR FuncPtrArray[5];

PTR_TO_FPTR_ARRAY FuncRetArrayPtr ()
{
FuncPtrArray[0] = Func1;
FuncPtrArray[1] = Func2;
return &FuncPtrArray;
}

int main()
{
cout << "Calling one ..." << FuncRetArrayPtr()[0][0](10) << endl;

cout << "Calling two ..." << FuncRetArrayPtr()[0][1](10) << endl;

return 0;
}

I have tried to make it as simple as posible. I am planing to write some more pragrams on function pointer. Some more example, and If somebody have some better idea , then please mail me , we can have a discussion . I am aslo planning to write some thing on dynamic casting , virtual mechanism, table, friends function , easy way of link list manupulation.....
cheer,
Sahu
hara.sahu@gmail.com

Problem with your Key Boad ,No proble, there is a way...:)


Hi ,

If you have problem with your Key board .say some of the letters are not working , then

there are ways , you can do it..

you can change your key board ..:) Hey Hey ... What yarr....:)


Steps

1) Go to start menu----> Run......> there you type osk then press eneter , you will see a key board , you can use it as your physical key board... ,it is like when you open citibank a/c on net , you see a key board , like this ....

is it not good thing?

Of course yes... :)


sahu

Function returning Pointer to array of function pointers

Function returning Pointer to array of function pointers

int (*(*FRAPtr())[5])(int);

We will discuss this .

as usual start from FRAPtr
So FRAPtr is a
Go to right we get Function ,
Function ...
now go to left , we find * ,nothing but returning a pointer to
So we get
returning pointer to ...
now the parentheses over.
So go right, we get an array of 5
to an array of 5 ...

Now go left , we find "*" which in nothing but pointers to
pointers to
Now the parentheses over;
Now go right ,we find (), which is nothing but function taking one integer argument
function taking one integer argument
Now go left whar we get , an integer , so it is returning int.
returning int

Whatever we have collected as of now , just put together .....

FRAPtr is a function, which returns a pointer to an array of 5, whose elements are function pointers, pointing to functions which takes an integer argument and returns an integer.


just relax ,

Example , illustrating the above declaration.

#include
int Func1(int x)
{
return x+x;
}
int Func2(int y)
{
return y+y;
}

int (*FuncPtrArray[5])(int);//it is global


int (*(*FuncRetArrayPtr())[5])(int)
{
FuncPtrArray[0] = Func1;
FuncPtrArray[1] = Func2;
return &FuncPtrArray;
}
int main()
{
cout << "Calling Func1 ..." << FuncRetArrayPtr()[0][0](10) << endl;
cout << "Calling Func2 ..." << (*FuncRetArrayPtr())[1](2) << endl;
return 0;
}

If you have any doubt , then please do mail me
hara.sahu@gmail.com
Cheer,
Sahu

Friday, August 17, 2007

Function returning a pointer to a function

Function returning a pointer to a function

void (*RetFtr())();

I am not surprised …. Because I know , I have formula to deals with. :)

Let us apply our 'magic formula' here also.

So starts with the variable name . i.e RetFptr… Kool Body … :)

RetFptr is a ..

Go to the right what we get a function taking no arguments.
So we get
function, (taking no arguments)
then go to left , what we get “*” that is pointer which is returned by the function ,Am I right , Assume , I can never be wrong… :)

so we get

which returns a pointer to ,

Now parentheses gets over;
Then go to right
What we get , it is again a function (which takes no arguments)
So we get
a function (which takes no arguments)

Now we go to left , here we find ,That function returns nothing i.e. void
that returns nothing or void.

Now we put together what we have collected as of now …. :)
So we get

RetFptr is a function, (taking no arguments) which returns a pointer to a function (which takes no arguments) that returns nothing or void.

Now we have done a good discussion , Lets do some practical …. :)

Example

void show()
{
printf("\n show()");
}


void (*RetFptr())()
{
return show;
}

Now, I need a pointer to RetFptr. How can I declare that?

I want a pointer to a function (*myFptr)() which, returns a function pointer,
Here I can write like this using the same formula… i.e Go right & Left .

(*(*myFptr)()) () of a function that takes no arguments and returns nothing (void)

void (*(*myFptr)()) ();

Here the below code does the same this what I have discussed above.
In main , I should have a pointer which can hold a RetFptr is a function, (taking no arguments) which returns a pointer to a function (which takes no arguments) that returns nothing or void.


#include
void show()
{
printf("\n show function ()\n");
}

void (*RetFptr())()
{
return show;
}

int main(int argc, char* argv[])
{
void (*(*ptr_to_fptr_ret_fptr)())();

ptr_to_fptr_ret_fptr = RetFptr;

ptr_to_fptr_ret_fptr()();

return 0;
}

All the example program i tested in my home pc,.GCC version 2.96
@ the Dollar prompt if you type gcc -v , you will get get some message , here i type that message
"gcc -v Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specsgcc version 2.96 20000731 (Red Hat Linux 7.1 2.96-98)"
here my compile version = 2.96,
and my OS = Red Hat Linux 7.1 2.
if you have any question regarding this program , Feel free to mail me.
hara.sahu@gmail.com
cheer,
sahu

Thursday, August 16, 2007

What Is a Function Pointer

What Is a Function Pointer ?

Function pointers are nothing but a pointer only Or we can say it is a pointer variable which points to the address of a function.

How To Define a Function Pointer ?
As I rightly told that it is a simply pointer variable , so we can declare it as usual manner.
So we can declare it both in C and C++.In C++ ,it points to member function of the class or a const member function of the class .

First we will discuss in C , then in C++

Ptf= pointer to function
Ptmf= pointer to member function
Ptcmf = pointer to const member function

int (*ptf)(int) = NULL; // in C
int (MyClass::*ptmf)(float, char) = NULL; // C++
int (MyClass::*ptcmf)(int) const = NULL; // C++

So in general we can say it is something like :
return type (* function pointer name ) (arguments);
As we know once we declare a variable , generaly we initialise it to NULL or 0 depending on type of variable... :)
So it is a good practice to initialize function pointers with NULL.

Wednesday, August 15, 2007

How to read function pointer ,sahu has one formula to read and write it. Kool :)

Hi,
I have tried to simplyfy to read and write the function pointer with some self developed rule. Just apply this rule.It may be coincidence with others.....But i have tried to make it easy to read and understan....:)In previous example i just tried to use it , but this time i tried to explain it. I would welcome, if someone suggest a batter way that must be an easy way of reading and writing it.
.....................................................................................
Function Pointers:
Here is an example of a function pointer.
Void (*fPtr)(void );
Here, fPtr is a pointer to a function, which takes nothing and returns nothing.

Here we will practice reading of some expression.

Like int * p;
How do we read the above declaration?
Rule is…. 1)
The answer is to start with from the name of the variable, here it is p.
Rule 2) Go to right then come back Rule 3) then go left. And finish the reading always.


So here start with variable p.
P is a….
R 2 Go right …. Nothing is there , just leave
R 3 go left of the variable P i.e *
Pointer to
Go right nothing is there , just leave ,
Go left, int is there so… read int
If you add together all the readings then it should be like this

P is a pointer to integer. Is this not a easy way of remembering? It will help us to read function pointer. Just go right , just finish reading, then go left… do this practice, you will be end of with reading the whole function pointer, no need to by heart the expression.

Now we will take an example of function pointer.

Example 1
Void (*fPtr)(void );
Lets use our formula here, and as I told , start with the variable name. here it is fPtr.
Step 1) rule 1 …What is there to the right of fPtr? Ans= Nothing. So leave it.
Step 2, apply rule 2... What is there to the left of fPtr? Ans = * and with this our reading finished within the parenthesis. Am I correct? Yes…..
So now we got

;- fPtr is a pointer to

Boss reading finished, just come out parenthesis,
What is there to the right of parenthesis? Ans = (void) which is nothing but function taking no argument (void) …..Cool :)
So now we got

Function taking no argument….

Reading finished, go to left … What is there to left of parenthesis? Ans = void, which is a return type of function… Am I right? Yes Boss….. Cool :)
So now we go

Returning void

Now we will adding all that we got from reading right and left of the starting variable name fPtr.

“fPtr is a pointer to Function taking no argument Returning void “

How easy it is …..:) Is not it?
I have done one example for you .Now Big Boss you have to help me to read one more for me.

Example 2

Int myArr[3])(int);
Boss it is easy, just apply my formula, then you will feel, it is dam easy.
:)
:)



What I have to tell? Ok we both will help each other…cool :)

1) Lets start with variable name ,i.e myArr. Ok…
2) Go right , we find array notation of 3 ok…
3) So we got
4) “myArr is an array of 3”
5) Go left ,we find “*” ,
6) So we got
7) “ Pointers to “
8) Come out parentheses ,because nothing is left there.
9) Go to the right of parentheses ,we find “(int) which is indicator of function.
10) So we got
11) “Function taking one argument as integer”
12) Go left , here it returns an integer.
13) So we got
14) “returns an integer”
15) Just add together what we got from our reading by using our formula.
16) myArr is an array of 3 Pointers to Function taking one argument as integer and returns an integer
Ha ha ha hi hi hi hu hu hu… cool.
Do we need an example program for this..? After lunch we need some sweets. Kuch mitha ho jaye.. :)


#include

int show1(int a)
{
printf("\n show1 a=%d",a);
return 1;
}
int show2(int c)
{
printf("\n show2 c=%d",c);
return 2;
}

int main()
{
int (*myArr[3])(int);

myArr[0] = show1;
myArr[1] = show2;

myArr[0](10);

myArr[1](20);
return 0;
}

From Sahu
hara.sahu@gmail.com

Tuesday, August 14, 2007

function pointer in c example

#include

typedef struct
{
void (*func)(int );
}myTest;

void show(int a)
{
printf("%d\n",a);
}

int main(void)
{
myTest tt;
int x=90;
tt.func = show;

tt.func(x);

return 0;
}

Function Pointer in a class or stucture

Hi ,
This program show how do we declare a function pinter as our class member .With i have tried to use the function pointer.It is self explanatory.If somebody have some doubt then pls mail me. hara.sahu@gmail.com

#include
using namespace std;

typedef int (*add)(int a,int b);
typedef int (*sub)(int a,int b);

int show(int a,int b)
{
cout<return a;
}

class Calculator
{
add _add;
sub _sub;

public:

Calculator(add a, sub b ) : _add(a), _sub(b) {}

int Add(int val1, int val2 )
{
return _add( val1, val2 ) ;
}

int Sub(int val1, int val2 )
{
return _sub(val1, val2 );
}
};
int main()
{
Calculator cc( show, show );
cc.Add(11,22);
}

sed command 's use

sed ‘3q’ /etc/passwd
Meanning :-
Quits after reading 3 lines.

$ sed ‘1,3p’ /etc/passwd

Sed by default prints all lines it processed on standard output. A p command will cause line 1 to 3 be printed twice

$ sed –n ‘1,3p’ /etc/paswd

It suppresses duplicate lines. Remember to user –n whenever using p command.

$ sed –n ‘9,11p’ /etc/passwd


Selects lines numbers 9 through 11.

The s (substitute) helps us in replacing a pattern in the file with something else. The syntax is -

s///

$ sed ‘1,5s/director/member /’emp.lst

The instruction replaces the left-most occurrence of the string director in the current line with the string member

$ sed ‘s/:/ /g’ /etc/passwd

Replaces all occurrences of : with a space with the g flag.

grep command

The grep command searches through one or more files for lines containing a target and then prints all of the matching lines it finds.
Multiline search should be enclosed within brackets otherwise grep will treat all others words as filename except the first one.

unix stuffs

The linked file is a pointer to the actual file Both the files have the separate inode numbers
We can have Symbolic linked files across different file systems
$ ln –s employee.lst emp