C++ Programming HOWTO
C++ Programming HOWTO
Table of Contents
C++ Programming HOW−TO...........................................................................................................................1
Al Dev (Alavoor Vasudevan) alavoor@yahoo.com...............................................................................1
1. Introduction..........................................................................................................................................1
2. String Class Varieties..........................................................................................................................1
3. Best C++ compilers for MS Windows 2000/NT/95/98/ME/XP .........................................................1
4. Download String .................................................................................................................................1
5. How Can I trust Al Dev's String Class ?? ...........................................................................................1
6. Usage of String class............................................................................................................................1
7. String.h file..........................................................................................................................................1
8. Renaming the String class....................................................................................................................2
9. File Class..............................................................................................................................................2
10. C++ Zap (Delete) function ................................................................................................................2
11. Pointers are problems ........................................................................................................................2
12. Usage of my_malloc and my_free ....................................................................................................2
13. Debug files.........................................................................................................................................2
14. Java like API......................................................................................................................................2
15. IDE tools for C++ .............................................................................................................................2
16. C++ Online Textbooks and Docs......................................................................................................2
17. C++ Coding Standards.......................................................................................................................2
18. C++ Online Docs...............................................................................................................................2
19. Memory Tools....................................................................................................................................2
20. Related URLs.....................................................................................................................................2
21. C++ Scripting Languages..................................................................................................................2
22. Templates...........................................................................................................................................3
23. STL References .................................................................................................................................3
24. Threads in C++..................................................................................................................................3
25. C++ Utilities......................................................................................................................................3
26. Other Formats of this Document........................................................................................................3
27. Translations To Other Languages......................................................................................................3
28. Copyright...........................................................................................................................................3
29. Appendix A String Program Files ....................................................................................................3
1. Introduction..........................................................................................................................................3
1.1 C++ v/s Java.......................................................................................................................................4
1.2 Which one Ada95, "C", "C++" or Java ??.........................................................................................4
1.3 Problems facing the current C++ compilers......................................................................................5
1.4 COOP − C++ Object Oriented Programming−language...................................................................6
2. String Class Varieties.........................................................................................................................7
2.1 Multiple Inheritance − Sample Custom String class ........................................................................7
3. Best C++ compilers for MS Windows 2000/NT/95/98/ME/XP ........................................................8
4. Download String ................................................................................................................................9
5. How Can I trust Al Dev's String Class ?? ..........................................................................................9
6. Usage of String class............................................................................................................................9
6.1 Operators..........................................................................................................................................10
6.2 Functions..........................................................................................................................................11
7. String.h file........................................................................................................................................11
7.1 StringBuffer.h..................................................................................................................................17
7.2 StringTokenizer.h.............................................................................................................................18
8. Renaming the String class..................................................................................................................19
i
C++ Programming HOW−TO
Table of Contents
8.1 Case 1: Simple rename.....................................................................................................................19
8.2 Case 2: Resolve conflict...................................................................................................................19
9. File Class............................................................................................................................................20
10. C++ Zap (Delete) function .............................................................................................................20
11. Pointers are problems .....................................................................................................................21
12. Usage of my_malloc and my_free .................................................................................................22
12.1 Garbage Collector for C++ ..........................................................................................................24
13. Debug files.......................................................................................................................................24
14. Java like API....................................................................................................................................24
15. IDE tools for C++ ..........................................................................................................................24
16. C++ Online Textbooks and Docs...................................................................................................25
17. C++ Coding Standards.....................................................................................................................26
18. C++ Online Docs.............................................................................................................................27
18.1 C++ Tutorials.................................................................................................................................28
18.2 Useful links....................................................................................................................................28
18.3 C++ Quick−Reference...................................................................................................................28
18.4 C++ Usenet Newsgroups...............................................................................................................28
19. Memory Tools..................................................................................................................................29
20. Related URLs...................................................................................................................................29
21. C++ Scripting Languages................................................................................................................29
21.1 PIKE (C/C++ Scripting Language)................................................................................................30
21.2 SoftIntegration Ch (C/C++ Scripting Language)...........................................................................30
21.3 PHP (C++ Scripting Language).....................................................................................................30
22. Templates.........................................................................................................................................30
23. STL References ..............................................................................................................................31
23.1 Overview of the STL ....................................................................................................................32
23.2 Header Files...................................................................................................................................33
23.3 The Container Classes Interface ...................................................................................................33
23.4 Vectors ..........................................................................................................................................34
Constructing Vectors ...............................................................................................................34
Checking Up on Your Vector ..................................................................................................35
Accessing Elements of a Vector ..............................................................................................36
Inserting and Erasing Vector Elements ...................................................................................37
Vector Iterators ........................................................................................................................38
Comparing Vectors ..................................................................................................................39
23.5 Iterators and the STL.....................................................................................................................40
23.6 Lists................................................................................................................................................40
23.7 Sets ................................................................................................................................................40
Constructing Sets......................................................................................................................40
What are Function Objects?......................................................................................................42
A Printing Utility......................................................................................................................44
How Many Elements?...............................................................................................................45
Checking the Equality of Sets...................................................................................................45
Adding and Deleting Elements.................................................................................................46
Finding Elements......................................................................................................................47
Set Theoretic Operations..........................................................................................................48
23.8 Maps...............................................................................................................................................50
23.9 STL Algorithms.............................................................................................................................51
ii
C++ Programming HOW−TO
Table of Contents
24. Threads in C++................................................................................................................................51
24.1 Threads Tutorial.............................................................................................................................51
24.2 Designing a Thread Class in C++..................................................................................................51
Introduction...............................................................................................................................52
Brief Introduction To Threads..................................................................................................52
Basic Approach.........................................................................................................................52
The Implementation..................................................................................................................52
Using The Thread Class............................................................................................................54
Conclusion................................................................................................................................54
25. C++ Utilities....................................................................................................................................54
26. Other Formats of this Document......................................................................................................55
26.1 Acrobat PDF format.....................................................................................................................56
26.2 Convert Linuxdoc to Docbook format .........................................................................................56
26.3 Convert to MS WinHelp format ..................................................................................................56
26.4 Reading various formats ..............................................................................................................57
27. Translations To Other Languages....................................................................................................57
28. Copyright.........................................................................................................................................58
29. Appendix A String Program Files .................................................................................................58
iii
C++ Programming HOW−TO
Al Dev (Alavoor Vasudevan) [email protected]
v40.4, 19 Sep 2001
This document provides a comprehensive list of C++ URL pointers, links to C++ online textbooks, and
programming tips on C++. This document also provides a C++ library which imitates Java−language, and
which has various methods to avoid memory problems in C++. Using this library you can compile Java's
source code under C++. This document serves as a "Home of C++ language". The information given here
will help you to program properly in C++ language and applies to all the operating systems that is − Linux,
MS DOS, BeOS, Apple Macintosh OS, Microsoft Windows 95/98/NT/2000, OS/2, IBM OSes (MVS, AS/400
etc..), VAX VMS, Novell Netware, all flavors of Unix like Solaris, HPUX, AIX, SCO, Sinix, BSD, etc.. and to
all other operating systems which support "C++" compiler (it means almost all the operating systems on this
planet).
1. Introduction
• 1.1 C++ v/s Java
• 1.2 Which one Ada95, "C", "C++" or Java ??
• 1.3 Problems facing the current C++ compilers
• 1.4 COOP − C++ Object Oriented Programming−language
7. String.h file
• 7.1 StringBuffer.h
• 7.2 StringTokenizer.h
9. File Class
10. C++ Zap (Delete) function
11. Pointers are problems
12. Usage of my_malloc and my_free
• 12.1 Garbage Collector for C++
22. Templates
23. STL References
• 23.1 Overview of the STL
• 23.2 Header Files
• 23.3 The Container Classes Interface
• 23.4 Vectors
• 23.5 Iterators and the STL
• 23.6 Lists
• 23.7 Sets
• 23.8 Maps
• 23.9 STL Algorithms
1. Introduction
The purpose of this document is to provide you with a comprehensive list of URL pointers and programming
tips on C++. Also, this document provides a C++ library having Java−like String class, string tokenizer,
memory functions and many other functions, which can be used in general C++ applications. Also various
examples are given here which demonstrate the usage of this library.
This document is not a textbook on C++, and there are already several excellent "on−line Text books" on
internet. If you are new to C++ and you never programmed in C++, then it is strongly suggested that you first
read the online C++ Textbooks given in the chapter C++ Online Textbooks and then follow the subsequent
chapters. It is suggested that you purchase a textbook on C++ for reference from online bookstores like
22. Templates 3
C++ Programming HOW−TO
amazon or barnes.
Because of manual memory allocations, debugging the C++ programs consumes a major portion of time.
This document will give you some better ideas and tips to reduce the debugging time.
Java is much closer to Ada95 than C++. Java is derived from Ada95. Ada95 gets the maximum points as per
David Wheeler's Ada comparison chart. Ada got 93%, Java 72%, C++ 68% and C got 53%. C++ and Java are
closer in points(only 4% difference), hence Java is not a very big revolution as compared to C++. On other
hand, Ada is a very big revolution and improvement over C++. The scores are like 4 students taking exams
and student with highest score is Ada (93%). Who knows? Perhaps in future Ada95 will replace Java!!
Development costs of Ada is half of C++ as per Stephen F. Zeigler. Ada95 is available at −
Since C++ programmers are abundant, it is recommended you do programming in object−oriented "C++" for
all your application programming or general purpose programming. You can take full advantage of object
oriented facilities of C++. The C++ compiler is lot more complex than "C" compiler and C++ programs may
run bit slower than "C" programs. But speed difference between "C" and "C++" is very minute − it could be
few milli−seconds which may have little impact for real−time programming. Since computer hardware is
becoming cheaper and faster and memory 'RAM' is getting faster and cheaper, it is worth doing code in C++
rather than "C" as time saved in clarity and re−usability of C++ code offsets the slow speed. Compiler
optimizer options like −O or −O3 can speed up C++/C which is not available in Java.
Nowadays, "C" language is primarily used for "systems programming" to develop operating systems, device
drivers etc..
Note: Using the String, StringBuffer, StringTokenizer and StringReader classes given in this howto, you
can code in C++ which "exactly" looks like Java. This document tries to close the gap between C++ and
Java, by imitating Java classes in C++
Java is platform independent language more suitable for developing GUI running inside web−browsers (Java
applets) but runs very slow. Prefer to use web−server−side programming "Fast−CGI" with C++ and HTML,
DHTML, XML to get better performance. Hence, the golden rule is "Web−server side programming use
C++ and web−client side (browser) programming use Java applets". The reason is − the server−side OS
(Linux) is under your control and never changes, but you will never know what the client side web−browser
OS is. It can be Internet appliance device (embedded linux+netscape) or computers running Windows
95/98/NT/2000 or Linux, Apple Mac, OS/2, Netware, Solaris etc..
The advantage of Java language is that you can create "Applets (GUI)" which can run on any client OS
platform. Java was created to replace the Microsoft Windows 95/NT GUI APIs like MS Visual Basic or MS
Visual C++. In other words − "Java is the cross−platform Windows−GUI API language of next century".
Many web−browsers like Netscape supports Java applets and web−browser like Hot Java is written in java
itself. But the price you pay for cross−platform portability is the performance, applications written in Java run
very slow.
In "C" programming − memory leaks, memory overflows are very common due to usage of features like −
The usage of char * and strcpy causes horrible memory problems due to "overflow", "fence past errors",
"memory corruption", "step−on−others−toe" (hurting other variable's memory locations) or "memory leaks".
The memory problems are extremely hard to debug and are very time consuming to fix and trouble−shoot.
Memory problems bring down the productivity of programmers. This document helps in increasing the
productivity of programmers via different methods addressed to solve the memory defects in "C++". Memory
related bugs are very tough to crack, and even experienced programmers take several days or weeks to debug
memory related problems. Memory bugs may be hide inside the code for several months and can cause
unexpected program crashes. The memory bugs due to usage of char * and pointers in C/C++ is costing $2
billion every year in time lost due to debugging and downtime of programs. If you use char * and pointers in
C++ then it is a very costly affair, especially if your program size is greater than 10,000 lines of code.
Hence, the following techniques are proposed to overcome the faults of "C" language. Give preference in the
following order −
To use "C char *", you would put all your "C" programs in a separate file and link to "C++" programs using
the linkage−specification statement extern "C" −
extern "C" {
#include <stdlib.h>
}
extern "C" {
comp();
some_c_function();
}
The extern "C" is a linkage specification and is a flag that everything within the enclosing block
(brace−surrounded) uses C linkage, not C++ linkage.
The 'String class' utilises the constructor and destructor features to automate memory management and
provides access to functions like ltrim, substring, etc..
See also related 'string class' in the C++ compiler. The string class is part of the standard GNU C++ library
and provides many string manipulation functions. Because the C++ 'string class' and 'String class' library
provides many string manipulation functions, there is less need to use the character pointer approach to write
your own string functions. Also, C++ programmers must be encouraged to use 'new', 'delete' operators instead
of using 'malloc' or 'free'.
The 'String class' does everything that char * or char [] does. It can completely replace char datatype. Plus
added benefit is that programmers do not have to worry about the memory problems and memory allocation
at all.
Therefore, I propose that we create a new version of C++ that does not allow the use of the bad features of C.
I propose that this new version of C++ be called COOP (say koop), which is an acronym for C++ Object
Oriented Programming−language" . COOP should be pronounced like chicken coop. (The logo of COOP
language is a big fat Hen inside coop!) I propose that the file extension for COOP files be .coo, which will
not conflict with .c for C programs or .cpp for C++ programs.
To begin with, write the COOP as a front end to C++. That is COOP pre−processes the code syntax and then
uses the standard C++ compiler to compile the program. COOP acts as a front end to C++ compiler. (To start
with, COOP will be a very good project/thesis topic for university students)
• COOP will borrow some best ideas from Microsoft C#, Microsoft put lot of efforts, and you can
• Java − Sun Microsystem put lot of effort, and you can simply utilize that.
• Connective C++ at http://www.quintessent.com/products/cc++.
• If none of these alternatives are suitable, you can build your own string class. You can start with one
or more of the pre−built classes listed above (by using single or multiple inheritance.)
Start by downloading the sample file 'string_multi.h' from Appendix A . That file is reproduced below:
// ******************************************************************
// Sample program to demonstrate constructing your own string class
// by deriving from the String class and stdlib's "string" class
// ******************************************************************
#ifndef __STRING_MULTI_H_
#define __STRING_MULTI_H_
#include <string>
#include "String.h"
#endif // __STRING_MULTI_H_
The String class in this document is tested with all the above compilers. It works fine with MS Visual C++
compiler v6.0, Borland C++ v5.2, Borland C++ compiler v5.5.1 and Bloodshed compiler.
4. Download String
All the programs, examples are given in Appendix of this document. You can download as a single tar zip,
the String class, libraries and example programs from
The program example_String.cpp (and also given in Appendix A ) has regression test module which you can
use to run the regression tests several millions of times automatically. After running the regression tests on
the String class you can certify that the String class program is a ROCK SOLID and a
BULLET−PROOF program.
I tested the String class with repeat cycle = 50000 and it ran and completed the program without crash.
While it is running I did not notice any memory leak. On linux, I used /usr/bin/gtop, unix top command,
KDEStart−>System−>KDE System Gaurd and KDEStart−>System−>Process management to monitor the
cpu and memory usage.
I recommend that you start the regression test with repeat cycle equal to 10 million or greater. The greater
the repeat cycle number the greater will be your confidence!! Start the test and go to lunch (or go drink
gharam chai − "chai peeke auvo") and come back to see the results!!
The 'String class' is a complete replacement for char and char * datatype. You can use 'String class' just like
char and get much more functionalities. You should link with the library 'libString.a' which you can build
4. Download String 9
C++ Programming HOW−TO
from the makefile given in Appendix A and copy the library to /usr/lib or /lib directory where all the "C++"
libraries are located. To use the 'libString.a' compile your programs like −
String aa;
6.1 Operators
The 'String class' provides these operators :−
• Equal to ==
• Not equal to !=
• Assignment =
• Add to itself and Assignment +=
• String concatenation or addition +
For example to use operators −
String aa;
String bb("Bill Clinton");
6.1 Operators 10
C++ Programming HOW−TO
6.2 Functions
The functions provided by String class has the same name as that of Java language's String class. The
function names and the behaviour is exactly same as that of Java's String class. StringBuffer class is also
provided. This will facilitate portability of code between Java and C++ (you can cut and paste and do
minimum changes to code). The code from Java's function body can be copied into C++ member function
body and with very mininum changes the code will compile under C++. Another advantage is that developers
coding in both Java and C++ do not need to remember two different syntax or function names.
String aa;
aa = 34 + 234.878;
cout << "The value of aa is : " << aa.val() << endl;
// The output aa will be '268.878'
Refer to Appendix A String.h for details about the String class function names. The same file String.h is
reproduced here in next section.
7. String.h file
In C++ (or any object oriented language), you just read the "class data−structure" (i.e. interface) to begin
using that object. You just need to understand the interface and not the implementation of the interface. In
case of String class, you just need to read and understand the String class in String.h file. You do not need to
read the entire implementation (String.cpp) in order to use String class. The object oriented classes are real
time saver and they very neatly hide the implementation.
(In object oriented Java language there is the equivalent called 'interface' , which hides the implementation
details.)
//
// Author : Al Dev Email: [email protected]
// Use string class or String class
//
// To prevent memory leaks − a char class to manage character variables
6.2 Functions 11
C++ Programming HOW−TO
#ifndef __STRING_H_ALDEV_
#define __STRING_H_ALDEV_
//class StringBuffer;
// I compiled and tested this string class on Linux (Redhat 7.1) and
// MS Windows Borland C++ version 5.2 (win32). This should also work
// using MS Visual C++ compiler
class String
{
public:
String();
String(const char bb[]); // needed by operator+
String(const char bb[], int start, int slength); // subset of chars
String(int bb); // needed by operator+
String(unsigned long bb); // needed by operator+
String(long bb); // needed by operator+
String(float bb); // needed by operator+
String(double bb); // needed by operator+
String(const String & rhs); // Copy Constructor needed by operator+
//String(StringBuffer sb); // Java compatibility − but causes compile problem on
String(int bb, bool dummy); // for StringBuffer class
virtual ~String(); // Made virtual so that when base class is deleted
// then the derived class destructor is c
6.2 Functions 12
C++ Programming HOW−TO
String toUpperCase();
String toLowerCase();
//////////////////////////////////////////////////////
// List of additonal functions not in java
//////////////////////////////////////////////////////
6.2 Functions 13
C++ Programming HOW−TO
String ltrim();
void ltrim(bool dummy); // Directly changes object. dummy to get different signat
String rtrim();
void rtrim(bool dummy); // Directly changes object. See also chopall().
// dummy to get different signature
void chopall(char ch='\n'); // removes trailing character 'ch'. See also rtrim()
void chop(); // removes one trailing character
bool isNull();
bool isInteger();
bool isInteger(int pos);
bool isNumeric();
bool isNumeric(int pos);
bool isEmpty(); // same as length() == 0
bool isUpperCase();
bool isUpperCase(int pos);
bool isLowerCase();
bool isLowerCase(int pos);
bool isWhiteSpace();
bool isWhiteSpace(int pos);
bool isBlackSpace();
bool isBlackSpace(int pos);
bool isAlpha();
bool isAlpha(int pos);
bool isAlphaNumeric();
bool isAlphaNumeric(int pos);
bool isPunct();
bool isPunct(int pos);
bool isPrintable();
bool isPrintable(int pos);
bool isHexDigit();
bool isHexDigit(int pos);
bool isCntrl();
bool isCntrl(int pos);
bool isGraph();
bool isGraph(int pos);
6.2 Functions 14
C++ Programming HOW−TO
void clear();
int toInteger();
long parseLong();
double toDouble();
String token(char separator = ' '); // see also StringTokenizer, explode()
String crypt(char *original, char *salt);
String getline(FILE *infp = stdin); // see also putline()
//String getline(fstream *infp = stdin); // see also putline()
void substring(int startIndex, int endIndex, bool dummy); // Directly changes obj
void reverse(bool dummy); // Directly changes object. dummy to get different sign
String deleteCharAt(int loc, bool dummy); // Directly changes object
String deleteStr(int startIndex, int endIndex, bool dummy);
void trim(bool dummy); // Directly changes object. dummy to get different signatu
String insert(int index, String str2);
String insert(int index, String str2, bool dummy); // Directly changes object
String insert(int index, char ch);
String insert(int index, char ch, bool dummy); // Directly changes object
String insert(char *newstr, int start = 0, int length = 0, char padchar = ' ');
String dump(); // Dump the string like 'od −c' (octal dump) does
///////////////////////////////////////////////
// List of duplicate function names
///////////////////////////////////////////////
// char * c_str() // use val()
// bool find(); // Use regionMatches()
// bool search(); // Use regionMatches()
// bool matches(); // Use regionMatches()
// int rindex(String str2, int startIndex = 0); Use lastIndexOf()
// String blanks(int slength); // Use repeat()
6.2 Functions 15
C++ Programming HOW−TO
String& operator+= (const String & rhs); // using reference will be faster
String& operator= (const String & rhs); // using reference will be faster
bool operator== (const String & rhs); // using reference will be faster
bool operator== (const char *rhs);
bool operator!= (const String & rhs);
bool operator!= (const char *rhs);
char operator [] (unsigned long Index) const;
char& operator [] (unsigned long Index);
friend ostream & operator<< (ostream & Out, const String & str2);
friend istream & operator>> (istream & In, String & str2);
bool String::operator< (const char *rhs) const; // handy methods for map & vector
bool String::operator< (const String & rhs) const; // handy methods for map & vec
protected:
char *sval; // Not safe to make sval public
6.2 Functions 16
C++ Programming HOW−TO
void verifyIndex(unsigned long index) const; // not "inline" because MS Win32 com
void verifyIndex(unsigned long index, char *aa) const;// not "inline" − MS Win32
private:
// Note: All the private variables and functions begin
// with _ (underscore)
#endif // __STRING_H_ALDEV_
7.1 StringBuffer.h
//
// Author : Al Dev Email: [email protected]
//
#ifndef __STRINGBUFFER_H_ALDEV_
#define __STRINGBUFFER_H_ALDEV_
7.1 StringBuffer.h 17
C++ Programming HOW−TO
public:
StringBuffer();
~StringBuffer();
StringBuffer(char *aa);
StringBuffer(int size);
StringBuffer(String str);
int capacity();
StringBuffer append(String str2);
// See also operator +
//{ *this += str2; return *this;} // This is causing core dumps...
StringBuffer reverse();
private:
StringBuffer *_pStringBuffer;
inline void allocpStringBuffer();
inline void Common2AllCstrs();
};
#endif // __STRINGBUFFER_H_ALDEV_
7.2 StringTokenizer.h
//
// Author : Al Dev Email: [email protected]
//
#ifndef __STRINGTOKENIZER_H_ALDEV_
#define __STRINGTOKENIZER_H_ALDEV_
int countTokens();
7.2 StringTokenizer.h 18
C++ Programming HOW−TO
bool hasMoreElements();
bool hasMoreTokens();
String nextElement(); // in java returns type 'Object'
String nextToken();
String nextToken(String delimiters);
private:
int CurrentPosition; // current index on string
int TotalTokens;
int RemainingTokens;
char * ListOfDl; // list of delimiters
char * WorkStr; // temp work string
char * OrigStr; // original string passed
bool DlFlag; // delimiter flag
inline void vPrepWorkStr(char *delimiters = NULL);
};
#endif // __STRINGTOKENIZER_H_ALDEV_
In all the files where you do include String.h, insert these lines:
// If you do not like the class name String, then you can rename using typedef
typedef String StringSomethingElseIwant;
.......etc...
}
The pre−processor will replace all literals of String to "String_somethingelse_which_I_want" and immdiately
undefines String. After undef the conflicting string class header file is included which defines the "String"
class.
9. File Class
You would use the File class to manipulate the operating system files. This class is an imitation of Java's File
class and will be very useful in C++ programming. Using this File class in C++ you can do if file exists() ?, if
directory exists() ?, file length() and other functions.
To make delete operators even more cleaner, make a Zap() inline function. Define a zap() function like this:
9. File Class 20
C++ Programming HOW−TO
// In C++ the reason there are 2 forms of the delete operator is − because
// there is no way for C++ to tell the difference between a pointer to
// an object and a pointer to an array of objects. The delete operator
// relies on the programmer using "[]" to tell the two apart.
// Hence, we need to define zaparr function below.
// To delete array of pointers
template <class T>
inline void zaparr(T & x)
{
{assert(x != NULL);}
delete [] x;
x = NULL;
}
The zap() function will delete the pointer and set it NULL. This will ensure that even if multiple zap()'s are
called on the same deleted pointer then the program will not crash. Please see the function zap_example() in
example_String.cpp.
zap(pLastname);
zap(pJobDescription);
There is nothing magical about this, it just saves repetative code, saves typing time and makes programs more
readable. The C++ programmers often forget to reset the deleted pointer to NULL, and this causes annoying
problems causing core dumps and crashes. The zap() takes care of this automatically. Do not stick a typecast
in the zap() function −− if something errors out on the above zap() function it likely has another error
somewhere.
Also my_malloc() , my_realloc() and my_free() should be used instead of malloc(), realloc() and free(), as
they are much cleaner and have additional checks. For an example, see the file "String.h" which is using the
my_malloc() and my_free() functions.
WARNING : Do not use free() to free memory allocated with 'new' or 'delete' to free memory allocated with
malloc. If you do, then results will be unpredictable.
Avoid using pointers as much as possible and use references. Pointers are really a great pain. It is possible to
write an application without using pointers. You should pointers only in those cases where references will not
work.
A reference is an alias; when you create a reference, you initialize it with the name of another object, the
target. From the moment on, the reference acts as an alternative name of the target, and anything you do to
the reference is really done to the target.
Syntax of References: Declare a reference by writing the type, followed by the reference operator (&),
followed by the reference name. References MUST be initialized at the time of creation. For example −
int weight;
int & rweight = weight;
DOG aa;
DOG & rDogRef = aa;
Do's of references −
Do not's of references −
The my_malloc and my_realloc is defined as below. It allocates little more memory (SAFE_MEM = 5) and
initializes the space and if it cannot allocate it exits the program. The 'call_check(), remove_ptr()' functions
are active only when DEBUG_MEM is defined in makefile and are assigned to ((void)0) i.e. NULL for
non−debug production release. They enable the total−memory used tracing.
See my_malloc.cpp. and the header file my_malloc.h. for full implementation of the my_malloc program.
char *aa;
int *bb;
float *cc;
aa = (char *) my_malloc(sizeof(char)* 214);
bb = (int *) my_malloc(sizeof(int) * 10);
cc = (float *) my_malloc(sizeof(int) * 20);
Note that in my_realloc you do not need to cast the datatype as the variable itself is passed and correct
my_realloc is called which returns the proper datatype pointer. The my_realloc has overloaded functions for
char*, int* and float*.
See the file debug.cpp for implementation of debug routines. And see the file my_malloc.cpp for sample
which uses debug.h and debug functions.
• The "top rated" Dev−C++ is an full−featured Integrated Development Environment (IDE) for both
Win32 and Linux. It uses GCC, Mingw or Cygwin as compiler and libraries set. It is at
http://www.bloodshed.net/devcpp.html and at mirror−site
• KDE Kdevelop
• Blatura site C++ Tools
• Amulet Amulet
• App Dev suite Angoss
• Make replacement Brass
• All public variables must begin with m like mFooVar. The m stands for member.
• All protected variables must begin with mt, like mtFooVar and methods with t, like tFooNum().
The t stands for protected.
• All private variables must begin with mv, like mvFooVar and methods with v, like vFooLone(). The
v stands for private.
• All public, protected and private variables must begin with uppercase after m like F in mFooVar.
• All pointer variables must be prefixed with p, like
♦ Public variables mpFooVar and methods like FooNum()
♦ Protected variables mtpFooVar and methods with t like tFooNum()
♦ Private variables mvpFooVar and methods with v like vFooNum()
The compiler should generate error if the code does not follow above standard. The C++ compiler can
provide a flag option to bypass strict coding standard to compile old source code, and for all new code being
developed will follow the uniform world−wide coding standard.
In the sample code given below t stands for protected, v stands for private, m stands for
member−variable and p stands for pointer.
class SomeFunMuncho
{
public:
int mTempZimboniMacho; // Only temporary variables should be public as per OO
float *mpTempArrayNumbers;
int HandleError();
float getBonyBox(); // Public accessor as per OOP design
float setBonyBox(); // Public accessor as per OOP design
protected:
float mtBonyBox;
int *mtpBonyHands;
char *tHandsFull();
int tGetNumbers();
private:
float mvJustDoIt;
char mvFirstName[30];
int *mvpTotalValue;
char *vSubmitBars();
int vGetNumbers();
};
When your program grows by millions of lines of code, then you will greatly appreciate the naming
convention as above. The readability of code improves, because just by looking at the variable name like
mvFirstName you can tell that it is member of a class and is a private variable.
See also
Internet has vast amounts of documentation on C++. Visit the search engines like Yahoo, Lycos, Infoseek,
Excite. Type in the keywords 'C++ tutorials' 'C++ references' 'C++ books' . You can narrow down the
search criteria by clicking on Advanced search and select search by exact phrase
• http://www.yahoo.com
• http://www.lycos.com
• http://www.infoseek.com
• http://www.excite.com
• http://www.mamma.com
• On linux contrib cdrom see mem_test*.rpm package and at http://www.rpmfind.net go here and
search mem_test.
• On linux cdrom see ElectricFence*.rpm package and at http://www.rpmfind.net go here and search
electricfence.
• Search the Internet engines like Yahoo, Lycos, Excite, Mamma.com for keyword "Linux memory
debugging tools".
unproductive. Since modern CPU's and RAM are becoming extremely fast and cheap, it is better to spend
more money on hardware and use scripting languages for development.
As memory (RAM) prices are dropping and CPU speeds are increasing, scripting language like PIKE will
EXPLODE in popularity. PIKE will become most widely used scripting language as it is object oriented
and it's syntax is very identical to that of C++ language.
Programming productivity will increase by five times by using the Pike C++ scripting language. And Pike is
very useful for 'proof of concept' and developing prototypes rapidly.
The Roxen Web server is completely written in Pike, which demonstrates how powerful Pike is. Pike runs
much faster than Java for some operations and is quite efficient in using memory resources.
The scripting language environment called Ch is a superset of C with high−level extensions, and salient
features from C++ and other languages so that users can learn the language once and use it anywhere for
almost any programming purposes. This C−compatible scripting language environment is also a middleware
serving as crucial software infrastructure for running portable applications in heterogeneous platforms. The
portable Ch code can be deployed safely over the internet or intranets to run anywhere ranging from
supercomputers, workstations, PCs, Palm Pilots, PDA, to non−traditional computing devices such as CNC
machines, robots, TVs, refrigerators, among others.
22. Templates
• http://babbage.cs.qc.edu/STL_Docs/templates.htm Mirror at:
http://www.mike95.com/c_plusplus/tutorial/templates
• For certification of C++: goto http://examware.com and click on "Tutorials" and then C/C++ button
STL Tutorial:
• Iterators. These are pointer like objects that allow the user to step through the contents of a container.
• Generic Algorithms. The STL provides a wide range of efficently implemented standard algorithms
(for example find, sort and merge) that work with the container types. (Some of the containers have
special purpose implementations of these algorithms as member functions.)
• Function Objects. A function object is an instance of a class that provides a definition of operator().
This means that you can use such an object like a function.
• Allocators. Every STL container class uses an Allocator class to hold information about the memory
model the program is using. I shall totally ignore this aspect of the STL.
I will be considering the use of the vector, list, set and map containers. To make use of these containers you
have to be able to use iterators so I shall have something to say about STL iterators. Using the set and map
containers can mean having to supply a simple function object to the instantiation so I shall also have
something to say about function objects. I will only briefly mention the algorithms supplied by the STL. I
will not mention adaptors at all.
I have taken liberties with some of the types of function arguments −− for example most of the integer
arguments referred to in what follows actually have type size_type which is typedef'ed to an appropriate basic
type depending on the allocation model being used. If you want to see the true signatures of the various
functions discussed have a look at the Working Paper or the header files.
There are a number of utility classes supplied with the STL. The only one of importance to us is the pair
class. This has the following definition:
};
as well as implementations of operator== and operator < . There is nothing complicated about this template
class and you should be able to use it without further guidance. To use it #include the header file pair.h. It
crops up in a number of places but particularly when using the set and map classes.
If you don't want to remember which is which you could just use stl.h which includes all the above (and all
the other header files of the STL as well).
[] element
* *
access/modification
insert insert element(s) * * * *
push_back insert new last element * *
push_front insert new first element *
erase remove element(s) * * * *
pop_back remove last element * *
pop_front remove last element *
Container
Class
Interface
If the following discussion leaves something unclear (and it will) you can always write a small test program
to investigate how some function or feature behaves.
23.4 Vectors
A vector is an array like container that improves on the C++ array types. In particular it is not neccessary to
know how big you want the vector to be when you declare it, you can add new elements to the end of a vector
using the push_back function. (In fact the insert function allows you insert new elements at any position of
the vector, but this is a very inefficent operation −− if you need to do this often consider using a list instead).
Constructing Vectors
vector is a class template so that when declaring a vector object you have to state the type of the objects the
vector is to contain. For example the following code fragment
vector<int> v1;
vector<string> v2;
vector<FiniteAutomaton> v3;
declares that v1 is a vector that holds integers, v2 a vector that holds strings and v3 holds objects of type
FiniteAutomaton (presumably an user defined class type). These declarations do not say anything about how
large the vectors are to be (implementations will use a default starting size) and you can grow them to as
large as you require.
vector<char> v4(26);
which says that v4 is to be vector of characters that initially has room for 26 characters. There is also a way to
initailise a vector's elements. The declaration
23.4 Vectors 34
C++ Programming HOW−TO
vector<float> v5(100,1.0);
says that v5 is a vector of 100 floating point numbers each of which has been initialised to 1.0.
<vector−size.cc>=
#include <iostream.h>
#include <vector.h>
void main()
{
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10,7);
To check on wether your vector is empty or not you can use the empty function. This takes no arguments and
returns a boolean value, true if the vector is empty, false if it is not empty. What will be printed out by the
following small program (true prints as 1 and false prints as 0)?
<vector−empty.cc>=
#include <iostream.h>
#include <vector.h>
void main()
{
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10,7);
cout << "v1.empty() has value " << v1.empty() << endl;
cout << "v2.empty() has value " << v2.empty() << endl;
cout << "v3.empty() has value " << v3.empty() << endl;
}
vector<int> v;
// ...
for (int i=0; i<v.size(); i++)
cout << v[i];
(which is very similar to what you might write for a builtin array).
You can also use operator[] to set the values of the elements of a vector.
vector<int> v;
// ...
for (int i=0; i<v.size(); i++)
v[i] = 2*i;
The function front gives access to the first element of the vector.
vector<char> v(10,'a');
// ...
char ch = v.front();
vector<char> v(10,'a');
// ...
v.front() = 'b';
The function back works the same as front but for the last element of the vector.
vector<char> v(10,'z');
// ...
char last = v.back();
v.back() = 'a';
<vector−access.cc>=
#include <vector.h>
#include <iostream.h>
void main()
{
vector<int> v1(5);
int x;
cout << "Enter 5 integers (seperated by spaces):" << endl;
for (int i=0; i<5; i++)
cin >> v1[i];
cout << "You entered:" << endl;
for (int i=0; i<5; i++)
cout << v1[i] << ' ';
cout << endl;
}
Note that insert and erase are expensive operations on vectors. If you use them a lot then you should consider
using the list data structure for which they are more efficient.
<vector−mod.cc>=
#include <iostream.h>
#include <vector.h>
void main()
{
vector<int> v;
int a1[5];
for (int i=0; i<5; i++) a1[i] = 100;
In the above a vector v has been declared then initialised using push_back. Then some elements have been
trimmed off it's end using pop_back. Next an ordinary integer array has been created and then some of its
elements inserted into v using insert. Finally erase has been used to remove elements from v. The functions
used above take arguments as follows.
• push_back takes a single argument of the type of the elements held in the vector.
• pop_back takes no arguments. It is a mistake to use pop_back on an empty vector.
• insert has three forms:
♦ insert(pos, T& x) which will insert the single element x at position pos in the vector.
♦ insert(pos, start, end) which inserts a sequence of elements from some other container at
position pos in the vector. The
♦ sequence of elements is identified as starting at the start element and continuing to, but not
including, the end element.
♦ insert(pos, int rep, T& x) inserts rep copies of x at position pos in the vector.
As indicated in the code above the position pos should be the address of the element to insert at, whilst the
start and end arguments are likewise also addresses. (The true story is that they are iterators −− see next
subsection and following section).
• erase has two forms (pos, start and end have the same types as for the insert function):
♦ erase(pos) which will remove the element at position pos in the vector.
♦ insert(start,end) which will remove elements starting at postion start upto, but not including,
the element at position end.
Vector Iterators
The simple way to step through the elements of a vector v is as we have done above:
Another way is to use iterators. An iterator can be thought of as a pointer into the container, incrementing the
iterator allows you to step through the container. For container types other than vectors iterators are the only
way to step through the container.
vector<T> v;
vector<T>::iterator i;
Vector Iterators 38
C++ Programming HOW−TO
Such iterators are constructed and returned by the functions begin() and end(). You can compare two iterators
(of the same type) using == and !=, increment using ++ and dereference using *. [In fact vector iterators
allow more operations on them − see next section for more information].
<vector−iterator.cc>=
#include <iostream.h>
#include <vector.h>
void main()
{
vector<int> v(10);
first is ``less'' than the second
int j = 1;
vector<int>::iterator i;
Note how *i can be used on the left−hand side of an assignment statement so as to update the element pointed
at by i, and on the right−hand side to access the current value.
Comparing Vectors
You can compare two vectors using == and <. == will return true only if both vectors have the same number
of elements and all elements are equal. The < functions performs a lexicographic comparison of the two
vectors. This works by comparing the vectors element by element. Suppose we are comparing v1 and v2 (that
is v1 < v2?). Set i=0. If v1[i] < v2[i] then return true, if v1[i] > v2[i] then return false, otherwise increment i
(that is move on to the next element). If the end of v1 is reached before v2 return true, otherwise return false.
Lexicographic order is also known as dictionary order. Some examples:
Comparing Vectors 39
C++ Programming HOW−TO
<vector−comp.cc>=
#include <vector.h>
#include <iostream.h>
void main()
{
vector<int> v1;
vector<int> v2;
for (int i=0; i<4; i++) v1.push_back(i+1);
for (int i=0; i<3; i++) v2.push_back(i+1);
cout << "v1 < v2 is: " << (v1<v2 ? "true" : "false") << endl;
}
23.6 Lists
See the section STL References
23.7 Sets
The set container type allows an user to store and retrieve elements directly rather than through an index into
the container. The set container acts as a mathematical set in that it holds only distinct elements. However
unlike a mathematical set, elements in a set container are held in (an user−supplied) order. In practise this is
only a minor restriction on treating a set container as an implementation of the mathematical set abstract data
type, and it allows for a much more efficent implementation than an unordered approach.
Constructing Sets
Two template arguments are required to construct a set container −− the type of the objects the set is to
contain and a function object that can compare two elements of the given type, that is:
set<T, Compare> s;
(The declaration set < T > s should also be possible −− it would use a default template argument less < T > as
the second argument, but many C++ compilers (including g++) cannot as yet cope with default template
arguments.)
For simple types T we can use the function object less < T > ( without having to worry about what a
``function object'' is), for example all the following are legal set declarations.
(Note that the space between the two final >'s in the template is required − otherwise the compiler will
interpret >> as the right shift operator.) In each of these cases the function object makes use of the operator <
as defined for the the underlying type (that is int, double, char and string).
The following code declares a set of integers, then adds some integers to the set using the insert method and
then prints out the set members by iterating through the set. You will note that the set's contents are printed
out in ascending order even though they were added in no particular order.
<set−construct1.cc>=
#include <iostream.h>
#include <set.h>
void main()
{
set<int, less<int> > s;
set<int, less<int> >::iterator i;
s.insert(4);
s.insert(0);
s.insert(−9);
s.insert(7);
s.insert(−2);
s.insert(4);
s.insert(2);
Note that 4 is added twice but only turns up once on the list of elements −− which is what one expects of a
set.
<function−object.cc>=
#include <iostream.h>
template<class T>
class square {
public:
T operator()(T x) { return x*x; }
};
// This can be used with any T for which * is defined.
void main()
{
// Create some function objects.
square<double> f1;
square<int> f2;
// Use them.
cout << 5.1^2 = << f1(5.1) << endl;
cout << 100^2 = << f2(100) << endl;
Function objects are used in a number of places in the STL. In particular they are used when declaring sets
and maps.
The function object required for these purposes, let's suppose it is called comp, must satisfy the following
requirements.
1. If comp(x,y) and comp(y,z) are true for objects x, y and z then comp(x,z) is also true.
2. comp(x,x) is false for every object x.
If for any particular objects x and y, both comp(x,y) and comp(y,x) are false then x and y are deemed to be
equal.
This, in fact, is just the behaviour of the strictly−less−than relation (ie < ) on numbers. The function object
less < T > used above is defined in terms of a < operator for the type T. It's definition can be thought of as
follows.
template<class T>
struct less {
(The actual definition uses references, has appropriate const annotations and inherits from a template class
binary_function.)
This means that if the type T has operator < defined for it then you can use less < T > as the comparator when
declaring sets of T. You might still want to use a special purpose comparator if the supplied < operator is not
appropriate for your purposes. Here is another example. This defines a simple class with a definition of
operator < and a function object that performs a different comparison. Note that the overloaded < and ()
operators should be given const annotations so that the functions work correctly with the STL.
<set−construct2.cc>=
#include <iostream.h>
#include <set.h>
// This class has two data members. The overloaded operator< compares
// such classes on the basis of the member f1.
class myClass {
private:
int f1;
char f2;
public:
myClass(int a, char b) : f1(a), f2(b) {}
int field1() const { return f1; }
char field2() const { return f2; }
bool operator<(myClass y) const
{ return (f1<y.field1()); }
};
void main()
{
set<myClass, less<myClass> > s1;
set<myClass, less<myClass> >::iterator i;
set<myClass, comp_myClass> s2;
set<myClass, comp_myClass>::iterator j;
s1.insert(myClass(1,'a'));
s2.insert(myClass(1,'a'));
s1.insert(myClass(1,'b'));
s2.insert(myClass(1,'b'));
s1.insert(myClass(2,'a'));
s2.insert(myClass(2,'a'));
The set s1 contains (1,a) and (2,a) as comparison is on the data member f1, so that (1,a) and (1,b) are deemed
the same element. The set s2 contains (1,a) and (1,b) as comparison is on the data member f2, so that (1,a)
and (2,a) are deemed the same element.
A Printing Utility
The way we have printed out the sets in the previous examples is a little awkward so the following header file
containing a simple overloaded version of operator<< has been written. It works fine for small sets with
simple element types.
<printset.h>=
#ifndef _PRINTSET_H
#define _PRINTSET_H
#include <iostream.h>
#include <set.h>
os << {;
while (cnt < sz−1)
{
os << *iter << ,;
iter++;
cnt++;
}
if (sz != 0) os << *iter;
os << };
return os;
}
#endif
The use here of << as an output routine for a set assumes that << has been defined for the set elements, and
uses this to print a comma delimited list of the set elements wrapped in curly braces. It will be used without
comment in the following examples.
A Printing Utility 44
C++ Programming HOW−TO
<set−size.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
void main()
{
set<int, less<int> > s;
s.insert(1);
s.insert(6);
s.insert(7);
s.insert(−7);
s.insert(5);
s.insert(2);
s.insert(1);
s.insert(6);
<set−equality.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
void main()
{
set<int, less<int> > s1, s2 ,s3;
It is also possible to compare two sets using <. The comparison s1 < s2 is true if the set s1 is
lexicographically less than the set s2, otherwise it is false.
For a set holding elements of type T these methods come in following forms:
• pair < iterator, bool> insert(T& x). This is the standard insert function. The return value may be
ignored or used to test if the insertion succeeded (that is the element was not already in the set). If the
insertion succeeded the boolean component will be true and the iterator will point at the just inserted
element. If the element is already present the boolean component will be false and the iterator will
point at the element x already present.
• iterator insert(iterator position, T& x). This version of the insert function takes, in addition to the
element to insert, an iterator stating where the insert function should begin to search. The returned
iterator points at the newly inserted element, (or the already present element).
• int erase(T& x). This version of the erase method takes an element to delete and returns 1 if the
element was present (and removes it) or 0 if the element was not present.
• void erase(iterator position). This version takes an iterator pointing at some element in the set and
removes that element.
• void erase(iterator first, iterator last). This verion takes two iterators pointing into the set and
removes all the elements in the range [ first,last ] .
<set−add−delete.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
void main()
{
set<int, less<int> > s1;
s1.insert(−2);
Finding Elements
We mention two member functions that can be used to test if an element is present in a set or not.
• iterator find(T& x). This searches for the element x in the set. If x is found it returns an iterator
pointing at x otherwise it returns end().
• int count(T& x). This returns 1 if it finds x in the set and 0 otherwise. (The count function for
multisets returns the number of copies of the element in the set which may be more than 1. Hence, I
guess, the name of the function.)
Finding Elements 47
C++ Programming HOW−TO
The use of find has been illustrated above. We could use count to write a simple template based set
membership function. (This should also provide a version that takes a reference to the argument x.)
<setmember.h>=
#ifndef _SETMEMBER_H
#define _SETMEMBER_H
#include <set.h>
<set−membership.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
#include setmember.h
void main()
{
set<int, less<int> > s;
for (int i= 0; i<10; i++) s.insert(i);
cout << s = << s << endl;
cout << 1 is << (member(1,s) ? : not) << a member of s
<< endl;
cout << 10 is << (member(10,s) ? : not) << a member of s
<< endl;
}
This checks to see if the set represented by the range [f2,l2] is included in the set [f1,l1]. It returns
true if it is and false otherwise. So to check to see if one set is included in another you would use
The includes function checks the truth of 3#3 ( that is of 4#4). This function assumes that the sets are
ordered using the comparison operator <. If some other comparison operator has been used this needs
to be passed to includes as an extra (function object) argument after the other arguments.
This forms the union of the sets represented by the ranges [f1,l1] and [f2,l2]. The argument result is
an output iterator that points at the start of the set that is going to hold the union. The return value of
the function is an output iterator that points at the end of the new set.
The fact that the result argument is an output iterator means that you cannot use set_union in the following,
natural, fashion:
The reason is that begin() (also end()) when used with sets (or maps) returns a (constant) input iterator. This
type of iterator allows you to access elements of the set for reading but not writing. (And this is a Good Thing
since if you could assign to a dereferenced iterator (as in (*i)= ...) then you could destroy the underlying order
of the set.)
The solution is to use an insert iterator based on the set type. This, basically, converts an assignment
(*i)=value (which is illegal) into a (legal) insertion s.insert(i,value) (where s is the set object that the iterator i
is pointing into). It is used as follows:
<set−theory.cc>=
#include <iostream.h>
#include <set.h>
#include <algo.h>
#include <iterator.h>
#include printset.h
void main()
{
typedef set<int, less<int> > intSet;
// Is s1 a subset of s2?
bool test = includes(s2.begin(),s2.end(),s1.begin(),s1.end());
cout << s1 subset of s2 is << (test ? true. : false.) << endl;
// Is s3 a subset of s1?
test = includes(s1.begin(),s1.end(),s3.begin(),s3.end());
cout << s3 subset of s1 is << (test ? true. : false.) << endl;
// Which is symmetric!
s4.erase(s4.begin(),s4.end());
set_symmetric_difference(s2.begin(), s2.end(), s1.begin(), s1.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s2 symmetric_difference s1 = << s4 << endl;
}
23.8 Maps
See the section STL References
23.8 Maps 50
C++ Programming HOW−TO
• QpThread Library for C++ provides object oriented framework in C++ for threads and Unix signals
on top of system level threads (currently POSIX Threads) http://lin.fsid.cvut.cz/~kra/index.html
• ThreadJack supports Java−like multi−thread programming model with platform independent C++
class library http://www.esm.co.jp/divisions/open−sys/ThreadJack/index−e.html and here is the
download−site
• APE is the "APE Portable Environment" and class libraries for writing portable threaded servers in
C++, under UNIX (pthread) and Win32 API's. APE provides portable class abstraction for threads,
sockets, file handling, and synchronization objects. The goal of APE is to make writing threaded
servers in C++ both practical and convient, even for small and simple projects, and hence simplicity
and low runtime overhead are design goals http://www.voxilla.org/projects/projape.html
Introduction
Multi threaded programming is becomming ever more popular. This section presents a design for a C++ class
that will encapsulate the threading mechanism. Certain aspects of thread programming, like mutexes and
semaphores are not discussed here. Also, operating system calls to manipulate threads are shown in a generic
form.
Why use threads you might ask. Well threads can often improve the performance of an application and they
do not incur significant overhead to implement. They effectively give good bang for a buck. Imagine an
image server program that must service requests for images. The program gets a request for an image from
another program. It must then retieve the image from a database and send it to the program that requested it.
If the server were implemented in a single threaded approach, only one program could request at a time.
When it was busy retrieving an image and sending it to a requestor, it could not service other requests. Of
course one could still implement such a system without using threads. It would be a challenge though. Using
threads, one can very naturally design a system to handle multiple requests. A simple approach would be to
create a thread for each request received. The main thread would create this thread upon receipt of a request.
The thread would then be responsible for the conversation with the client program from that point on. After
retrieving the image, the thread would terminate itself. This would provide a smooth system that would
continue to service requests even though it was busy serviceing other requests at the same time.
Basic Approach
The create a thread, you must specify a function that will become the entry point for the thread. At the
operating system level, this is a normal function. We have to do a few tricks to wrap a C++ class around it
because the entry function cannot be a normal member function of a class. However, it can be a static
member function of a class. This is what we will use as the entry point. There is a gotcha here though. Static
member functions do not have access to the this pointer of a C++ object. They can only access static data.
Fortunately, there is way to do it. Thread entry point functions take a void * as a parameter so that the caller
can typecast any data and pass in to the thread. We will use this to pass this to the static function. The static
function will then typecast the void * and use it to call a non static member function.
The Implementation
It should be mentioned that we are going to discuss a thread class with limited functionality. It is possible to
do more with threads than this class will allow.
class Thread
{
public:
Thread();
Introduction 52
C++ Programming HOW−TO
};
Thread::Thread() {}
/*static */
void * Thread::EntryPoint(void * pthis)
{
Thread * pt = (Thread*)pthis;
pthis−>Run( Arg() );
}
It is important to understand that we are wrapping a C++ object around a thread. Each object will provide an
interface to a single thread. The thread and the object are not the same. The object can exist without a thread.
In this implementation, the thread does not actually exist until the Start function is called.
Notice that we store the user argument in the class. This is necessary because we need a place to store it
temporarily until the thread is started. The operating system thread call allows us to pass an argument but we
have used it to pass the this pointer. So we store the real user argument in the class itself and when the
execute function is called it can get access to the argument.
Introduction 53
C++ Programming HOW−TO
int Start(void * arg); This function provides the means to create the thread and start it going. The argument
arg provides a way for user data to be passed into the thread. Start() creates the thread by calling the operating
system thread creation function.
int Run(void * arg); This is a protected function that should never be tampered with.
static void * EntryPoint(void * pthis); This function serves as the entry point to the thread. It simply casts
pthis to Thread * and
virtual void Setup(); This function is called after the thread has been created but before Execute() is called.
If you override this function, remember to call the parent class Execute().
virtual void Execute(void *); You must override this function to provide your own functionality.
Conclusion
This section presented an implementation of a thread class written in C++. Of course it is a simple approach
but it provides a sound foundation upon which to build a more robust design.
• escape ISB for C++ − Provides information on how to develop and program distributed,
object−based applications in C++ for Windows and Unix using the Netscape Internet Service Broker
http://docs.iplanet.com/docs/manuals/enterprise/cpluspg/contents.htm
• http://www.linuxdoc.org and click on HOWTOs and search for howto document name using
CTRL+f or ALT+f within the web−browser.
You can also find this document at the following mirrors sites −
• http://www.caldera.com/LDP/HOWTO
• http://www.linux.ucla.edu/LDP
• http://www.cc.gatech.edu/linux/LDP
• http://www.redhat.com/mirrors/LDP
• Other mirror sites near you (network−address−wise) can be found at
http://www.linuxdoc.org/mirrors.html select a site and go to directory
/LDP/HOWTO/xxxxx−HOWTO.html
• You can get this HOWTO document as a single file tar ball in HTML, DVI, Postscript or SGML
formats from − ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO/other−formats/ and
http://www.linuxdoc.org/docs.html#howto
Single HTML file can be created with command (see man sgml2html) − sgml2html −split 0
xxxxhowto.sgml
• Translations to other languages like French, German, Spanish, Chinese, Japanese are in
ftp://www.linuxdoc.org/pub/Linux/docs/HOWTO and
http://www.linuxdoc.org/docs.html#howto Any help from you to translate to other languages is
welcome.
The document is written using a tool called "SGML−Tools" which can be got from −
http://www.sgmltools.org Compiling the source you will get the following commands like
• sgml2html xxxxhowto.sgml (to generate html file)
• sgml2html −split 0 xxxxhowto.sgml (to generate a single page html file)
• sgml2rtf xxxxhowto.sgml (to generate RTF file)
• sgml2latex xxxxhowto.sgml (to generate latex file)
Or you can use Ghostscript command ps2pdf. ps2pdf is a work−alike for nearly all the functionality of
Adobe's Acrobat Distiller product: it converts PostScript files to Portable Document Format (PDF) files.
ps2pdf is implemented as a very small command script (batch file) that invokes Ghostscript, selecting a
special "output device" called pdfwrite. In order to use ps2pdf, the pdfwrite device must be included in the
makefile when Ghostscript was compiled; see the documentation on building Ghostscript for details.
And you may have to manually edit some of the minor errors after running the perl script. For e.g. you may
need to put closing tag < /Para> for each < Listitem>
Then use the tool HtmlToHlp. You can also use sgml2rtf and then use the RTF files for generating winhelp
files.
And resize the window with mouse. To navigate use Arrow keys, Page Up, Page Down keys, also you can
use 'f', 'd', 'u', 'c', 'l', 'r', 'p', 'n' letter keys to move up, down, center, next page, previous page etc. To turn off
expert menu press 'x'.
You can read postscript file using the program 'gv' (ghostview) or 'ghostscript'. The ghostscript program is in
ghostscript*.rpm package and gv program is in gv*.rpm package in Redhat Linux which can be located
through ControlPanel | Applications | Graphics menu buttons. The gv program is much more user friendly
than ghostscript. Also ghostscript and gv are available on other platforms like OS/2, Windows 95 and NT,
you view this document even on those platforms.
• Get ghostscript for Windows 95, OS/2, and for all OSes from http://www.cs.wisc.edu/~ghost
gv howto.ps
ghostscript howto.ps
You can read HTML format document using Netscape Navigator, Microsoft Internet explorer, Redhat Baron
Web browser or any of the 10 other web browsers.
You can read the latex, LyX output using LyX a X−Windows front end to latex.
28. Copyright
Copyright policy is GNU/GPL as per LDP (Linux Documentation project). LDP is a GNU/GPL project.
Additional requests are that you retain the author's name, email address and this copyright notice on all the
copies. If you make any changes or additions to this document then you please intimate all the authors of this
document. Brand names mentioned in this document are property of their respective owners.
• Read the header file first and then see the example cpp program
♦ String.h http://www.angelfire.com/country/aldev0/cpphowto/String.h
♦ StringBuffer.h http://www.angelfire.com/country/aldev0/cpphowto/StringBuffer.h
♦ StringTokenizer.h http://www.angelfire.com/country/aldev0/cpphowto/StringTokenizer.h
♦ StringRW.h http://www.angelfire.com/country/aldev0/cpphowto/StringRW.h
♦ string_multi.h http://www.angelfire.com/country/aldev0/cpphowto/string_multi.h
♦ example_String.cpp http://www.angelfire.com/country/aldev0/cpphowto/example_String.cpp
• Debug facilities ..
♦ debug.h http://www.angelfire.com/country/aldev0/cpphowto/debug.h
♦ debug.cpp http://www.angelfire.com/country/aldev0/cpphowto/debug.cpp
♦ Makefile http://www.angelfire.com/country/aldev0/cpphowto/Makefile
28. Copyright 58
C++ Programming HOW−TO
28. Copyright 59