Sunday, January 8, 2012

Operator Oveloading




Basics of operator overloading
1. Overloading binary operators
2. Overloading the relational and logical operators
3. Overloading a unary operator
4. Using friend operator functions
5. A closer look at the assignment operator
6. Overloading the [ ]subscript operator


BASICS OF OPERATOR OVERLOADING
1.Allows the programmer to define the meaning of
the C++ operators relative to programmer
defined classes
2. Resembles function overloading
3. An operator is always overloaded relative to a
user-defined type, such as a class
4.When overloaded, the operator loses none of its
original meaning
5. To overload an operator, we create an operator
function
6. An operator function can be
-A member of the class for which it is defined
-A friend of the class for which it is defined

General form of a member operator function
return-type class-name::operator#(arg-list) { … }

Restrictions:
The precedence of the operator cannot be changed
The number of operands that an operator takes cannot be altered
The following operators cannot be overloaded
. :: .* ? preprocessor operators
Except for the =, operator functions are inherited by
any derived class.
Operator functions can be further overloaded in the
derived classes.
Operator functions cannot have default arguments.
Running Codes
class coord {
int x, y;
public:
coord(int a = 0, int b = 0) {
x = a; y = b;
}
void show() {
cout << x << “, ” << y <<
endl;
}
coord operator+(coord obj);
coord operator+(int i);
coord operator-(coord obj);
coord operator=(coord obj);
};

coord coord::operator+(coord
obj) {
coord temp;
temp.x = x + obj.x;
temp.y = y + obj.y;
return temp;
}
coord coord::operator+(int i) {
coord temp;
temp.x = x + i;
temp.y = y + i;
return temp;
}
coord coord::operator-(coord obj) {
coord temp;
temp.x = x - obj.x;
temp.y = y - obj.y;
return temp;
}
coord coord::operator=(coord obj) {
x = obj.x;
y = obj.y;
return *this;
}


Reference




A reference is an implicit pointer
* Acts like another name for a variable
* Can be used in three ways
* A reference can be passed to a function
* A reference can be returned by a function
* An independent reference can be created
* Reference variables are declared using the & symbol
Example: void f(int &n);

Unlike pointers, once a reference becomes
associated with a variable, it cannot refer to
other variables

Advantages
1. The address is automatically passed
2.Reduces use of ‘&’ and ‘*’
3.When objects are passed to functions using
references, no copy is made
Hence destructors are not called when the
functions ends
Eliminates the troubles associated with
multiple destructor calls for the same object
Running Codes
Using pointer:
void f(int *n) {
*n = 100;
}
void main() {
int i = 0;
f(&i);
cout << i; // 100
}

Using reference :
void f(int &n) {
n = 100;
}
void main() {
int i = 0;
f(i);
cout << i; // 100
}
http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29

Initialization, D estruction, and Copy

Now that num_sequence declares actual data members, we must provide for their initialization.
We could leave it to each derived class to initialize these data members, but that's potentiallyerror-prone. A better design is to provide a base class constructor to handle the initialization of all
base class members.
Recall that num_sequence is an abstract base class. We cannot define an independent object of its
class; rather, the num_sequence serves as a subobject of each derived cla ss object. For this reason,
we declare the base class constructor to be a protected rather than public member.
The initialization of a derived class object consists of the invocation of the base class constructor
followed by that of the derived class constructor. It helps to think of the derived class object as
consisting of multiple subobjects: a base class s ubobject initialized by the base class constructor
and a derived class subobject initialized by the derived class constructor. In a three-level class
hierarchy, such as the AudioBook class of Section 5.1, the derived class consists of three
subobjects, each one initialized by its respective constructor.
The design requirements of a derived class constructor are twofold: Not only must it initialize the
derived class data members, but it must also supply the expected values to its base class
constructor. In our example, the num_sequence base class requires three values that are passed to
it using the member initialization list. For example,


If we should overlook the invocation of the num_sequence constructor, the definition of the
Fibonacci constructor is flagged as an error. Why? The num_sequence base class requires our
explicit invocation of its three-argument constructor. In our design, this is what we want.
Alternatively, we could provide a default num_sequence constructor. We must change _relems
to a pointer, however, and add code to verify th at it is non-null before each access of the vector:


Running Codes
inline Fibonacci::
Fibonacci(int len, int beg_pos)
: num_sequence(len, beg_pos, &_elems)
{}


num_sequence::
num_sequence(int len=1, int bp=1, vector *pe=0)
: _length(len), _beg_pos(bp), _pelems(re){}

Exception Part 2(Example)





Running Codes
// exceptions_Exception_Examples.cpp
// compile with: /EHsc
#include

using namespace std;
void MyFunc( void );

class CTest
{
public:
CTest(){};
~CTest(){};
const char *ShowReason() const { return "Exception in CTest class."; }

};

class CDtorDemo
{
public:
CDtorDemo();
~CDtorDemo();
};

CDtorDemo::CDtorDemo()
{
cout << "Constructing CDtorDemo." << endl;
}

CDtorDemo::~CDtorDemo()
{
cout << "Destructing CDtorDemo." << endl;
}

void MyFunc()
{

CDtorDemo D;
cout<< "In MyFunc(). Throwing CTest exception." << endl;
throw CTest();
}

int main()
{
cout << "In main." << endl;
try
{
cout << "In try block, calling MyFunc()." << endl;
MyFunc();
}
catch( CTest E )
{
cout << "In catch handler." << endl;
cout << "Caught CTest exception type: ";
cout << E.ShowReason() << endl;
}
catch( char *str )
{
cout << "Caught some other exception: " << str << endl;
}
cout << "Back in main. Execution resumes here." << endl;
return 0;
}
http://www.cprogramming.com/tutorial/exceptions.html

Using an Inheritance Hierarchy

Let's presume we've defined the five other numeric sequence classes (Pell, Lucas, Square,
Triangular, and Pentagonal) in the same manner as the Fibonacci class. We now have a two-level
inheritance hierarchy: an abstract num_sequence base class and the six inheriting derived classes.
How might we use them?
Here is a simple display() function whose second parameter is ns, a const reference to a
num_sequence object.


Within display(), we call the two virtual functions what_am_i() and elem() . Which
instances of these functions are invoked? We cannot say for certain. We know that ns does not
refer to an actual num_sequence class object but rather to an object of a class derived from
num_sequence. The two virtual function calls are resolved at run-time based on the type of theclass object ns refers to. For example, in the following small program I define an object of each
derived class in turn and pass it to display():


Running Codes
inline void display(ostream &os,
const num_sequence &ns, int pos)
{
os << "The element at position "
<< pos << " for the "
<< ns.what_am_i() << " sequence is "
<< ns.elem(pos) << endl;
}


int main()
{
const int pos = 8;
Fibonacci fib;
display(cout, fib, pos);
Pell pell;
display(cout, pell, pos);
Lucas lucas;
display(cout, lucas, pos);
Triangular trian;
display(cout, trian, pos);
Square square;
display(cout, square, pos);
Pentagonal penta;
display(cout, penta, pos);
}

Defining an Abstract Base Class

In this section we redesign the num_sequence class of the preceding section in to an abstract base
class from which we inherit each of the numeric sequence classes. How do we go about that?
The first step in defining an abstract base class is to identify the set of operations common to its
children. For example, what are the operations common to all numeric sequence classes? These
operations represent the public interface of the num_sequence base class. Here is a first iteration:


elem() returns the element at the user-requested position. max_elems() returns the maximum
number of elements supported by our implementation. check_integrity() determines
whether pos is a valid position. print() displays the elements. gen_elems() generates the
elements for the sequence. what_am_i() returns a character string identifying the sequence. The next step in the design of an abstract base class is to identify which operations are type-dependent — that is, which operations require separate implementations based on the derived
class type. These operations become the virtual func tions of the class hierarchy. For example, each
numeric sequence class must provide a separate implementation of gen_elems() .
check_integrity(), on the other hand, is type-invariant. It must determine whether pos is a
valid element position. Its algorithm is independent of the numeric sequence. Similarly,
max_elems() is type-invariant. All the numeric sequences hold the same maximum number of
elements.
Not every function is this easy to distinguish. what_am_i() may or may not be type-dependent
depending on how we choose to implement our inheritance hierarchy. The same is true of elem()
and print(). For now, we'll presume that they are type-dependent. Later, we'll see an alternative
design that turns them into type-invariant functions. A static member function cannot be declared
as virtual.
The third step in designing an abstract base class is to identify the access level of each operation.
If the operation is to be available to the general program, we declare it as public . For example,
elem() , max_elems() , and what_am_i() are public operations.
If the operation is not meant to be invoked outside the base class, we declare it as private. A
private member of the base class cannot be accessed by the classes that inherit from the base class.
In this example, all the operations must be available to the inheriting classes, so we do not declare
any of them as private.
IA third access level, protected, identifies operations that are available to the inheriting classes
but not to the general program. check_integrity() and gen_elems() , for example, are
operations that the inheriting classes, but not the general program, must invoke. Here is our
revised num_sequence class definition:


Running Codes
class num_sequence {
public:
// elem(pos): return element at pos
// gen_elems(pos): generate the elements up to pos
// what_am_i() : identify the actual sequence
// print(os) : write the elements to os
//check_integrity(pos) : is pos a valid value?
// max_elems() : returns maximum position supported
int elem(int pos);
void gen_elems(int pos);
const char* what_am_i() const;
ostream& print(ostream &os = cout) const;
bool check_integrity(int pos);
static int max_elems();
// ...
};


class num_sequence {
public:
virtual ~num_sequence(){};
virtual int elem(int pos) const = 0;
virtual const char* what_am_i() const = 0;
static int max_elems(){ return _max_elems; }
virtual ostream& print(ostream &os = cout) const = 0;
protected:
virtual void gen_elems(int pos) const = 0;
bool check_integrity(int pos) const;
const static int _max_elems = 1024;
};

Exception Part1




Exceptions are run time anomalies or unusual
conditions that a program may encounter during
execution.
Conditions such as
*Division by zero Division by zero
*Access to an array outside of its bounds
*Running out of memory
*Running out of disk space
It was not a part of original C++.
It is a new feature added to ANSI C++.

Exceptions are of 2 kinds
1.Synchronous Exception:
Out of rage
Over flow
2.Asynchronous Exception: Error that are caused by
causes beyond the control of the program
Keyboard interrupts
In C++ only synchronous exception can be
handled.
Exception handling mechanism
Find the problem (Hit the exception)
Inform that an error has occurred (Throw the exception) Inform that an error has occurred (Throw the exception)
Receive the error information (Catch the exception)
Take corrective action (handle the exception)
EXCEPTION HANDLING MECHANISM

It is basically build
upon three keywords
Try
Throw
Catch
try block Detects and throws an exception
Catch
catch block
Catch

The keyword tryis used to preface a block of
statements which may generate exceptions.
When an exception is detected, it is thrown using a
throwstatement in the try block. throwstatement in the try block.
A catchblock defined by the keyword ‘catch’
catches the exception and handles it appropriately.
The catch block that catches an exception must
immediately follow the try block that throws the
exception.
EXCEPTIONHANDLINGMECHANISM(CONT…)
try
{

throw exception;

// Block of statements
// which detect and
// throws an exception …
}
catch(type arg)
{



}
// throws an exception
// catch exception
// Block of statement
// that handles the
// exception
Running Codes
http://www.cprogramming.com/tutorial/exceptions.html

String Part2





Running Codes
#include
#include
using namespace std;

int main()
{
string s1;
string s2("345");
string s3("678");
s1=s2;
cout << s1 << endl;
s1="012";
cout << s1 << endl;
s1=s1+s2+s3;
cout << s1 << endl;
s1+="9";
cout << s1 << endl;
s1.insert(0,s1);
cout << s1 << endl;
s1.insert(0,"abc");
cout << s1 << endl;
s1.erase(0,3);
cout << s1 << endl;
s1.replace(0,1,s1);
cout << s1 << endl;
cout << s1.at(0) << endl;
cout << s1.find("456") << endl;
cout << s1.substr(9,8) << endl;
return 0;


}

http://pages.cs.wisc.edu/~cs368-1/CppTutorial/NOTES/STRING.html

Creating an Http Handler in ASP

Creating an Http Handler

It’s possible to create a type that implements the IHttpHandlerinterface and have it respond
to any pattern of URL. The advantage is you have full control over the URL, and the URL of the
request doesn’t need to correspond to a physical file. The downside is that IIS configuration is
required to map the URL into the framework, and ASP.NET configuration is required to map
the URL to your specific handler.
The alternative is to use the built-in, simple handler factory. This handler is mapped to
files with an ASHX extension. The WebHandlerdirective is used to point an ASHX page at a type
that implements the IHttpHandlerinterface. Visual Studio adds a file with this directive to
your project via the Generic Handler option in the Add New Item dialog window.

Polymorphism without Inheritance

The num_sequence class of Section 4.10 simulates polymorphism. Each class object can be made
into any of the six numerical sequences at any point in the program through the set_sequence()
member function:

The ability to change the sequence type of ns is supported through programming rather than
through direct support of the language. Each class object contains an _isa data member that
identifies the current numeric sequence that it represents:




Running Codes
for (int ix = 1; ix < num_sequence::num_of_sequences(); ++ix)
{
ns.set_sequence(num_sequence::nstype(ix));
int elem_val = ns.elem(pos);
// ...
}


class num_sequence {
public:
// ...
private:
vector *_elem; // addresses current element vector
PtrType _pmf; // addresses current element generator
ns_type _isa; // identifies current sequence type
// ...
};

HTTP Handlers in ASP

HttpApplication is the type that manages the request as it moves through the pipeline. Up to
now we’ve examined the events along that pipeline and the mechanisms at your disposal for
extending its functionality. A critical step of that process is creating and executing the request
handler. The Pagehandler, which is an instance of System.Web.UI.Page(or any type derived
from that type), deals with ASPX pages. In this section we’re going to take a look at what it
takes to be a handler that the Framework recognizes, some of the other handlers that are built
into the Framework, and how to create your own handlers to custom process specialized
requests.
So what does it take to be a handler? How does the Framework know how deal with an
instance of the Pageclass, a derived type that didn’t exist at the time the Framework was
compiled? Via polymorphism, of course.
The only thing the pipeline cares about is a simple interface named IHttpHandler. Any
type that implements this interface qualifies to receive requests from the ASP.NET Framework
and process them however it sees fit. Once a type implements this interface, it’s associated
with requests via any combination of file name, file extension, or request type.
For example, the extension ASPX is mapped to the Page handler factory. The pipeline
hands the request off to this type by calling a method on the IHttpHandlerinterface. This class
looks at the request, creates an instance of the corresponding page object, and hands the request off to it via the same interface method.
Handlers Built into the Framework
A few handlers are built into the ASP.NET 1.x versions of the Framework, and ASP.NET 2.0 adds
quite a few more. Handlers can be used for any type of specialized request processing. They
can be mapped to a specific URL (as is the case with trace.axd), or the can be mapped to a
specific extension (as is the case with *.aspx).
Handlers can also respond to specific HTTP request types (GET, POST, HEAD, and oth-
ers). There actually is a handler that rejects outright any request type that is not a GET, POST,
or HEAD (the HttpMethodNotAllowedhandler).
Table 2-4 is a list of the handlers built into the Framework and a brief description of the
work that they do. A detailed discussion of some of the more prominent handlers follows.

Implementing an HttpModule ASP

The second method of extending the pipeline is to implement an HttpModule. Modules are
Microsoft’s intentional design for reusing pre- and post-processors across IIS applications.
The last technique you looked at (that of inheriting from HttpApplication in a standalone
assembly and reusing across IIS applications) has a serious limitation that modules don’t
have: You can only use one class per application (even though you can reuse that same class
across several applications).
HttpModules are designed so that several can be plugged into a single IIS application. The
extensions that Microsoft adds to the pipeline that you examined previously are implemented
as HttpModules. So by default, any IIS application has about a dozen modules plugged in and
extending the pipeline.
Modules are designed to be “plugged into” the pipeline using the web.configfile. You can
add a module to all IIS applications by adding it to the web.configat the root of a web server,
or you can add modules to specific applications by adding them to the web.configat the
virtual root of an application.
Under the system.webelement of the web.configis an HttpModules element. Any number
of modules can be added using child Add elements under the HttpModules element. Here’s a
configuration snippet that adds the module SomeModule
Running Codes



String Part 1




The string class is part of the C++ standard library. A string represents a sequence of characters.
To use the string class, #include the header file:
#include
Constructors:
string ()
- creates an empty string ("")
string ( other_string )
- creates a string identical to other_string
string ( other_string, position, count )
- creates a string that contains count characters from other_string, starting at position. If count is missing (only the first two arguments are given), all the characters from other_string, starting at position and going to the end of other_string, are included in the new string.
string ( count, character )
- create a string containing character repeated count times

MANIPULATING STRING OBJECTS
1.insert()
2.erase()
3.replace()
4.append()
More Methods IN String Class:

size():Number of elements currently
stored
length():Number of elements currently
stored
capacity():Total elements that can be stored
max_size():Maximum size of a string object
that a system can support
emply():Return true or 1 if the string is
empty otherwise returns false or 0
resize():Used to resize a string object
(effects only size and length)
at(): For accessing individual characters
substr(): For retrieving a substring
find(): For finding a specific substring
find_first_of(): For finding the location of first occurrence of the specific
character(s)
find_last_of(): For finding the location of first occurrence of the specific
character(s)
[] operator: For accessing individual character. Makes the string
object to look like an array.
Running Codes
http://pages.cs.wisc.edu/~cs368-1/CppTutorial/NOTES/STRING.html

How to Use Arrays and Vectors

Following are the first eight elements from six numerical sequences:
Fibonacci: 1, 1, 2, 3, 5, 8, 13, 21
Lucas: 1, 3, 4, 7, 11, 18, 29, 47
Pell: 1, 2, 5, 12, 29, 70, 169, 408
Triangular: 1, 3, 6, 10, 15, 21, 28, 36
Square: 1, 4, 9, 16, 25, 36, 49, 64
Pentagonal: 1, 5, 12, 22, 35, 51, 70, 92
Our program must display a pair of elements from a sequence and allow the user to guess the next element.
If the user guesses right and wishes to continue, the program then displays a second pair of elements, then
a third, and so on. How might we do that?
If succeeding element pairs are taken from the same sequence, the user, recogni zing one pair, recognizes
them all. That is not very interesting. So we'll pick an element pair from a different numeric sequence with
each iteration of the main program loop.
For now, we'll display a maximum of six element pairs per session: one pair from each of the six
sequences. We'd like to implement this so that we can loop through the display of the element pairs
without having to know which sequence we are disp laying with each loop iteration. Each iteration must
have access to three values: the element pair and the element that follows them in the sequence.
The solution we discuss in this section uses a container type that can hold a contiguous sequence of integer
values that we can reference not by name but by position within the container. We store 18 values in the
container as a collection of six tuples: The first two represent the element pair to display; the third
represents the next sequence element. With each iterati on of the loop, we add 3 to the index value, in this
way stepping through the six tuples in turn.
In C++, we can define a container as either a built-in array or an object of the stan-dard library vector class.
In general, I recommend the use of the vector class over that of the built-in array. However, a great deal of
existing code uses the built-in array, and it is important to understand how to use both representations.
To define a built-in array, we must specify the type of element the array is to hold, give the array a name,
and specify a dimension — that is, the number of elements the array can hold. The dimension must be a
constant expression — that is, an expression that does not require run-time evaluation. For example, the
following code declares pell_seq to be an array of 18 integer elements.

To define a vector class object, we must first include the vector header file. The vector class is a
template, so we indicate the type of its element in brackets following the name of the class. The dimension is placed in parentheses; it does not need to be a constant expression. The following code defines
pell_seq as a vector class object holding 18 elements of type int . By default, each element is initialized
to 0.


Running Codes
const int seq_size = 18;
int pell_seq[seq_size];


#include
vector pell_seq(seq_size);

Inheriting from HTTPApplication ASP part2

This will leverage the ASP.NET 1.x model for the global.asax, with the exception that, by
default, the class isn’t compiled until runtime (as is the case for any class in the code direc-
tory). The type will still show up via IntelliSense in the IDE, and you can still code against it in
a strongly typed manner.
To trap HttpApplicaiton events, you now have two options. The aforementioned naming
convention will work. Or you can add delegates to the base class events from the constructor.
The following class traps both the BeginRequestand PreRequestHandlerExecuteevents: one by
explicitly creating the trap; the other by using the naming convention. It also declares a static
field that will be available throughout the application:
using System;
using System.Web;
public class MyImpl : HttpApplication
{
public static string SomeStaic = "This is a static variable";
public MyImpl()
{
this.PreRequestHandlerExecute += new
EventHandler(MyImpl_PreRequestHandlerExecute);
}
void Application_OnBeginRequest(object sender, EventArgs e)
{
Response.Write("Entering BeginRequest
");
}
void MyImpl_PreRequestHandlerExecute(object sender, EventArgs e)
{
Response.Write("Entering PreRequestHandlerExecute
");
}
}

Vector Part2





Running Codes
#include
#include
using namespace std;

class Point
{
int x,y;
public:
Point()
{
}
Point(int x,int y)
{
this->x=x;
this->y=y;
}
int getX()
{
return this->x;
}
int getY()
{
return this->y;
}
};


// Display the vector contents by looping with size
void display(vector &v)
{
cout << endl;
for(int i=0;i<5;i++)
{
cout << "(" << v[i].getX() << "," << v[i].getY() << ") ";
}
cout << endl;
}

// Display the vector contents by iterator
void show(vector &v)
{
cout << endl;
vector::iterator p;
for(p=v.begin();p!=v.end();p++)
{
cout << "(" << (*p).getX() << "," << (*p).getY() << ") ";
cout << "(" << p->getX() << "," << p->getY() << ") ";
}
cout << endl;
}


int main()
{
vector v;
// Initial Size : 0
cout << "Initial Size : " << v.size() << endl;

for(int i=0;i<10;i++)
{
Point pt(i,i);
v.push_back(pt);
}
// Display
display(v);
cin.get();
return 0;
}



STL Description




The Standard Template Libraries (STL's) are a set of C++ template classes to provide common programming data structures
and functions such as doubly linked lists (list), paired arrays (map), expandable arrays (vector), large string storage
and manipulation (rope), etc. The STL library is available from the STL home page. This is also your best detailed
reference for all of the STL class functions available.

STL can be categorized into the following groupings:

Container classes:
Sequences:
vector: (this tutorial) Dynamic array of variables, struct or objects. Insert data at the end.
(also see the YoLinux.com tutorial on using and STL list and boost ptr_list to manage pointers.)
deque: Array which supports insertion/removal of elements at beginning or end of array
list: (this tutorial) Linked list of variables, struct or objects. Insert/remove anywhere.
Associative Containers:
set (duplicate data not allowed in set), multiset (duplication allowed): Collection of ordered data in a balanced binary tree structure. Fast search.
map (unique keys), multimap (duplicate keys allowed): Associative key-value pair held in balanced binary tree structure.
Container adapters:
stack LIFO
queue FIFO
priority_queue returns element with highest priority.
String:
string: Character strings and manipulation
rope: String storage and manipulation
bitset: Contains a more intuitive method of storing and manipulating bits.
Operations/Utilities:
iterator: (examples in this tutorial) STL class to represent position in an STL container. An iterator is declared to be associated with a single container class type.
algorithm: Routines to find, count, sort, search, ... elements in container classes
auto_ptr: Class to manage memory pointers and avoid memory leaks.
Running Codes


Inheriting from HttpApplication ASP

The code template for the code behind the global.asax has stubs of traps for a few events in
the request pipeline. Also present are Application_Start and Application_End, as well as
Session_Start and Session_End. These are holdovers from classic ASP. The application start
event is fired when the first instance of HttpApplication is created within an application
domain. Requests are processed within an IIS application from a pool of HttpApplication
objects.
Session start and end are fired as sessions are created and torn down. You can do your
own user-specific allocation and disposal of resources in traps of these events.
The events of the HttpApplication pipeline can be trapped by using a method naming
convention:
Public void Application_OnEventName(Object sender, EventArgs e)
The ASP.NET runtime gives global.asax special treatment. Even though there’s no code
creating the delegate and passing it to this event definition, code is generated behind the
scenes that sinks the event. This is a very VB-like strategy, telling the developer to “pay no
attention to the code generator behind the curtain.”
You also cannot override the default constructor and provide your own code to sink these
events, as the code generation that occurs at runtime also generates a default constructor for
the same class, resulting in a compile error when you provide your own default constructor.
There’s also no way to reference any public field defined at the class level with the inline
script model. Adding a public static field to this class definition is the recommended alterna-
tive to using the Application object. Accessing a static field is much quicker than doing a
lookup from the Application state bag. If any modifications are made to these fields, access
must be synchronized, of course. But this is the case with the Application object as well (it
provides the Lockand Unlockmethods to do this), and it’s best to use these fields for read-only
information you want to make available to your entire application.
However, with the inline script model, the class doesn’t exist until the code generation
step at runtime, and unlike most of the dynamically created classes in the ASP.NET 2.0 envi-
ronment, you cannot reference it within the integrated development environment (IDE) at
design time. This is true even when you add the ClassName attribute to the Application
directive.
For these reasons, as well as the other many benefits of the code-behind model, there are
benefits you can gain from using the ASP.NET 1.x model for the global.asax, instead of relying
on the template in ASP.NET 2.0.
When a global.asax is added to a Web project, the default template uses on inline script
block:

<%@ Application Language="C#" %>

<%@ Application Language="C#" %>

Writing Conditional and Loop Statements

By default, statements are executed once in sequence, beginning with the first statement of main() . In the
preceding section, we had a peek at the if statement. The if statement allows us to execute conditionally
one or a sequence of statements based on the truth evaluation of an expression. An optional else clause
allows us to test multiple truth conditions. A looping st atement allows us to repeat one or a sequence of
statements based on the truth evaluation of an expression. The following pseudo-code program makes use
of two looping statements ( #1 and #2), one if statement ( #5), one if-else statement ( #3), and a
second conditional statement called a switch statement ( #4).

The condition expression of the if statement must be within parentheses. If it is true, the statement
immediately following the if statement is executed:

If multiple statements must be executed, they must be enclosed in curly braces following the if statement
(this is called a statement block):
Running Codes
// Pseudo code: General logic of our program
while the user wants to guess a sequence
{ #1
display the sequence
while the guess is not correct and
the user wants to guess again
{ #2
read guess
increment number-of-tries count
if the guess is correct
{ #3
increment correct-guess count
set got_it to true
} else {
express regret that the user has guessed wrong
generate a different response based on the
current number of guesses by the user // #4
ask the user if she wants to guess again
read response
if user says no // #5
set go_for_it to false
}
}
}


// #5
if (usr_rsp == 'N' || usr_rsp == 'n')
go_for_it = false;


//#3
if (usr_guess == next_elem)
{ // begins statement block
num_right++;
got_it = true;
} // ends statement block


Count Session variables in ASP

This is a very simple interface, which exposes an integer for you to use to report the count
of session variables at the moment session state is restored.
This code allows you to move custom information from a preprocessor into an instance of
a request handler. To pass this information to any handler, the implementation needs only to
inherit from this interface:
public class CreateSessionVars : System.Web.UI.Page, ISessionCounter
{
private int _SessionVarCount;
public int SessionVarCount
{
get { return _SessionVarCount; }
set { _SessionVarCount = value; }
}
//Snip…
This page uses implementation inheritance with System.Web.UI.Pageas its base class, as
is the usual case for ASPX code-behinds, but then takes the additional step of implementing
the ISessionCounter interface. The page will now be instructed by the request preprocessor
as to how many session variables existed when the session state was first restored. It can do
whatever it needs to with this information. In this case, you’ll use it to expose a button to cre-
ate a user-selected number of session variables, and then track the deltas as postbacks occur.
Leveraging this interface-based approach to polymorphic handler types is a common
method to check type information on the handler in a preprocessor, and pass information
from the preprocessor pipeline into a handler. You can use custom attributes this way as well,
for an aspect-based approach yielding similar polymorphic behavior.
Running Codes
%@ Page language="c#"
CodeFile="CreateSessionVars.aspx.cs"
Inherits="CreateSessionVars" %>
private void btnSubmit_Click(object sender, System.EventArgs
{
int Count = int.Parse(txtCount.Text) + Session.Keys.Count
for (int i = Session.Keys.Count; i < Count; i++) { Session[string.Format("sessionvar{0}",i)] = i; } } private void btnSubmit_Click(object sender, System.EventArgs { int Count = int.Parse(txtCount.Text) + Session.Keys.Count for (int i = Session.Keys.Count; i < Count; i++) { Session[string.Format("sessionvar{0}",i)] = i; } }



Vector




In computing, sequence containers refer to a group of container class templates in the standard library of the C++ programming language that implement storage of data elements. Being templates, they can be used to store arbitrary elements, such as integers or custom classes. One common property of all sequential containers is that the elements can be accessed sequentially. Like all other standard library components, they reside in namespace std.

The following containers are defined in the current revision of the C++ standard: array, vector, list, forward_list, deque. Each of these containers implement a different algorithms for data storage, which means that they have different speed guarantees for different operations:[1]

array implements a compile-time non-resizeable array.
vector implements an array with fast random access and an ability to automatically resize when appending elements.
deque implements a double-ended queue with comparatively fast random access.
list implements a doubly linked list.
forward_list implements a singly linked list.

Running Codes
#include
#include
using namespace std;

// Display the vector contents by looping with size
void display(vector &v)
{
cout << endl;
for(int i=0;i<5;i++)
{
cout << v[i] << " ";
}
cout << endl;
}

// Display the vector contents by iterator
void show(vector &v)
{
cout << endl;
vector::iterator p;
for(p=v.begin();p!=v.end();p++)
{
cout << *p << " ";
}
cout << endl;
}


int main()
{
vector v;
// Initial Size : 0
cout << "Initial Size : " << v.size() << endl;

for(int i=0;i<10;i++)
{
// Insert at the back
v.push_back(i);
}
// Display
display(v);

v.pop_back(); // Pop from the back

cout << endl << v.front() << endl;

cout << endl << v.back() << endl;

// Display
display(v);

vector::iterator itr=v.begin(); // Get the iterator
itr+=3; // Iterator points to the 4th element
v.insert(itr,2,99); // Insert 99 twice into that position
display(v);

v.erase(v.begin()+3,v.begin()+5); // Remove 4th and 5th element
display(v);

v.erase(v.begin(),v.end()); // Remove all the elements
display(v);

cout << endl;

cin.get();
return 0;
}


http://www.cplusplus.com/reference/stl/vector/vector/

Operator Precedence

There is one ''gotcha'' to the use of the built-in operators: When multiple operators are combined in a single
expression, the order of expression evaluation is determined by a predefined precedence level for each
operator. For example, the result of 5+2*10 is always 25 and never 70 because the multiplication operator
has a higher precedence level than that of addition; as a result, 2 is always multiplied by 10 before the
addition of 5.
We can override the built-in precedence level by placing parentheses around the operators we wish to be
evaluated first. (5+2)*10 , for example, evaluates to 70.
For the operators I've introduced, the precedence order is listed next. An operator has a higher precedence
than an operator under it. Operators on the same line have equal precedence. In these cases, the order of
evaluation is left to right.


Running Codes
logical NOT
arithmetic (*, /, %)
arithmetic (+, -)
relational (<, >, <=, >=)
relational (==, !=)
logical AND
logical OR
assignment


Checking the size and capacity of the different types

Every variable in a C++ program must be giEarlier we mentioned thesizeofoperator that is used to determine the number
of bytes a given data type occupies in memory. The following program reports on
the sizes of the various basic data types we have discussed.

The output of this program depends on the computer on which it is run. The
following show the results of running this code on two different machines.

Notice that anintis 4 bytes on both machines and so, in both cases,intvariables
can hold values from−2
31
to 2
31
−1.
Note also thatdoublevariables on both machines are 8 bytes, but this does not
tell us the range of values thatdoublevalues can take.
For thefloatanddoubledata types, there are three quantities of interest: the
largest value, the smallest positive value, and the difference between 1 and the small-
est value greater than 1. This latter value is known as the epsilon value of the data
type. Knowing that a doubleis 8 bytes does not immediately reveal these three
quantities.
C++ provides header files with this information. The header fileclimitsgives
the minimum and maximum value of various integer types. It defines symbols such
asINT_MINandINT_MAXthat are equal to the smallest and largest value an int
may hold. Similarly, the header filecfloatgives the minimum positive, maximum,
and epsilon values forfloat, double, and long double(if available) data types.

Running Codes
#include
using namespace std;
/
**
*
Report on the size of various C++ data types.
*
*
This program may give different results when run on different
*
computers depending on how each of the fundamental data types is
*
defined on those platforms.
*
/
int main() {
// Integer types:
cout << "The size of short is " << sizeof(short)
<< " bytes" << endl;
cout << "The size of int is " << sizeof(int)
<< " bytes" << endl;
cout << "The size of long is " << sizeof(long)
<< " bytes" << endl;
// long long might not exist on all computers
cout << "The size of long long is " << sizeof(long long)
<< " bytes" << endl;
// Character and boolean types:
cout << "The size of char is " << sizeof(char) << " bytes" << endl;
cout << "The size of bool is " << sizeof(bool) << " bytes" << endl;
// Floating point types
cout << "The size of float is " << sizeof(float)
<< " bytes" << endl;
cout << "The size of double is " << sizeof(double)
<< " bytes" << endl;
// long double might not exist on all computers
cout << "The size of long double is " << sizeof(long double)
<< " bytes" << endl;
return 0;
}

The size of short is 2 bytes
The size of int is 4 bytes
The size of long is 4 bytes
The size of long long is 8 bytes
The size of char is 1 bytes
The size of bool is 4 bytes
The size of float is 4 bytes
The size of double is 8 bytes
The size of long double is 8 bytes
The size of short is 2 bytes
The size of int is 4 bytes
The size of long is 4 bytes
The size of long long is 8 bytes
The size of char is 1 bytes
The size of bool is 1 bytes
The size of float is 4 bytes
The size of double is 8 bytes
The size of long double is 12 bytes



Queue(Standard Template Library)




queues are a type of container adaptor, specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and extracted from the other.

queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed into the "back" of the specific container and popped from its "front".

The underlying container may be one of the standard container class template or some other specifically designed container class. The only requirement is that it supports the following operations:

front()
back()
push_back()
pop_front()




#include
#include
using namespace std;


int main()
{
queue q;
// Initial Size : 0
cout << "Initial Size : " << q.size() << endl;

for(int i=0;i<10;i++)
{
q.push(i);
}

int size=q.size();
for(int i=0;i<5; i++)
{
cout << q.front() << endl;
q.pop();

}

cout << endl;
cin.get();
return 0;
}

Stack




Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from the end of the container.

stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.

The underlying container may be any of the standard container class templates or some other specifically designed container class. The only requirement is that it supports the following operations:

back()
push_back()
pop_back()
Running Codes
#include
#include
using namespace std;



int main()
{
stack s;
// Initial Size : 0
cout << "Initial Size : " << s.size() << endl;

for(int i=0;i<10;i++)
{
s.push(i);
}

int size=s.size();
for(int i=0;ihttp://www.cplusplus.com/reference/stl/stack/



The integer types

Every variable in a C++ program must be given atype. The type of a variable is a
specification of the kind of data the variable can store. The most basic type isint.
Anintrepresents an integer quantity. Consider the following program

In this program, two variables, xandy, are declaredto be of type int. These
declarations occur on lines 5 and 6. C++ requires that we specify the type of every
variable, and the declaration statement is the manner by which this is accomplished.
Variables may be declared anywhere in the program so long as they are declared
before they are used.
Subsequently (lines 8 and 9) the variables areassignedvalues. In this casexis
assigned the value 3 andythe value 4. The equal sign =is an operation (called
assignment) that stores the value of the expression to its right into the variable on its
left.
It is possible to combine declarations on a single line; in place of lines 5 and 6, we
could have this:

It is possible to combine declaration with assignment. Lines 5–9 can be replaced
by these two:

It’s easy to see what the rest of Program 2.1 does. In line 11, the contents ofxand
yare added, and the result is written on the computer’s screen.
Running Codes
1 #include
2 using namespace std;
3
4 int main() {
5 int x;
6 int y;
7
8 x = 3;
9 y = 4;
10
11 cout << x+y << endl;
12
13 return 0;
14 }

int x,y;

int x = 3;
int y = 4;

STL(standard template library)




The Standard Template Libraries (STL's) are a set of C++ template classes to provide common programming data structures
and functions such as doubly linked lists (list), paired arrays (map), expandable arrays (vector), large string storage
and manipulation (rope), etc. The STL library is available from the STL home page. This is also your best detailed
reference for all of the STL class functions available.

STL can be categorized into the following groupings:

Container classes:
Sequences:
vector: (this tutorial) Dynamic array of variables, struct or objects. Insert data at the end.
(also see the YoLinux.com tutorial on using and STL list and boost ptr_list to manage pointers.)
deque: Array which supports insertion/removal of elements at beginning or end of array
list: (this tutorial) Linked list of variables, struct or objects. Insert/remove anywhere.
Associative Containers:
set (duplicate data not allowed in set), multiset (duplication allowed): Collection of ordered data in a balanced binary tree structure. Fast search.
map (unique keys), multimap (duplicate keys allowed): Associative key-value pair held in balanced binary tree structure.
Container adapters:
stack LIFO
queue FIFO
priority_queue returns element with highest priority.
String:
string: Character strings and manipulation
rope: String storage and manipulation
bitset: Contains a more intuitive method of storing and manipulating bits.
Operations/Utilities:
iterator: (examples in this tutorial) STL class to represent position in an STL container. An iterator is declared to be associated with a single container class type.
algorithm: Routines to find, count, sort, search, ... elements in container classes
auto_ptr: Class to manage memory pointers and avoid memory leaks.
Running Codes
http://en.wikipedia.org/wiki/Standard_Template_Library

Multiple Inheritance − Sample Custom String class in C++

C++ is one of the most powerful language and will be used for a long time in the future inspite of emergen
of Java. C++ runs extremely fast and is in fact 10 to 20 times FASTER than Java. Java runs very slow
because it is a byte−code−interpreted language running on top of "virtual machine". Java runs faster with
(Just−In−Time) compiler, but it is still slower than C++. And optimized C++ program is about 3 to 4 tim
faster than Java (with JIT compiler). Then, why do people use Java? Because it is pure object oriented and
easier to program in Java, as Java automates memory management, and programmers do not directly deal
with memory allocations. This document attempts to automate the memory management in C++ to make i
much more easy to use. The library given here will make C++ look like Java and will enable "C++" to
compete with Java language.
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.

Language choice is very difficult. There are too many parameters − people, people skills, cost, tools, politics
(even national politics) and influence of businessmen/commercial companies. The best language based on
technical merits does not get selected simply due to political decisions!
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 −
Ada home http://www.gnuada.org. •
Google Ada index •
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..
Running Codes
http://www.linuxselfhelp.com/HOWTO/C++Programming-HOWTO-3.html



#ifndef __STRING_MULTI_H_ALDEV_
#define __STRING_MULTI_H_ALDEV_

#include
#include "String.h"
#include "StringBuffer.h"

#ifdef NOT_MSWINDOWS
#else
using namespace std; // required for MS Visual C++ compiler Version 6.0
#endif

// Important Notes: In C++ the constructors, destructors and copy
// operator are NOT inherited by the derived classes!!
// Hence, if the operators like =, + etc.. are defined in
// base class and those operators use the base class's contructors
// then you MUST define equivalent constructors in the derived
// class. See the sample given below where constructors mystring(),
// mystring(char[]) are defined.
//
// Also when you use operator as in atmpstr + mstr, what you are really
// calling is atmpstr.operator+(mstr). The atmpstr is declared a mystring

class mystring:public String, string
{
public:
mystring():String() {} // These are needed for operator=, +
mystring(char bb[]):String(bb) {} // These are needed for operator=, +
mystring(char bb[], int start, int slength):String(bb, start, slength) {}
mystring(int bb):String(bb) {} // needed by operator+
mystring(unsigned long bb):String(bb) {} // needed by operator+
mystring(long bb):String(bb) {} // needed by operator+
mystring(float bb):String(bb) {} // needed by operator+
mystring(double bb):String(bb) {} // needed by operator+
mystring(const String & rhs):String(rhs) {} // Copy Constructor needed by operator+
mystring(StringBuffer sb):String(sb) {} // Java compatibility
mystring(int bb, bool dummy):String(bb, dummy) {} // for StringBuffer class

int mystraa; // customizations of mystring
private:
int mystrbb; // customizations of mystring
};

#endif // __STRING_MULTI_H_ALDEV_

C++ v/s Java

C++ is one of the most powerful language and will be used for a long time in the future inspite of emergen
of Java. C++ runs extremely fast and is in fact 10 to 20 times FASTER than Java. Java runs very slow
because it is a byte−code−interpreted language running on top of "virtual machine". Java runs faster with
(Just−In−Time) compiler, but it is still slower than C++. And optimized C++ program is about 3 to 4 tim
faster than Java (with JIT compiler). Then, why do people use Java? Because it is pure object oriented and
easier to program in Java, as Java automates memory management, and programmers do not directly deal
with memory allocations. This document attempts to automate the memory management in C++ to make i
much more easy to use. The library given here will make C++ look like Java and will enable "C++" to
compete with Java language.
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.

Language choice is very difficult. There are too many parameters − people, people skills, cost, tools, politics
(even national politics) and influence of businessmen/commercial companies. The best language based on
technical merits does not get selected simply due to political decisions!
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 −
Ada home http://www.gnuada.org. •
Google Ada index •
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..
Running Codes
http://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B

Designing a Thread Class in C++

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.
Brief Introduction To Threads
To understand threads one must think of several programs running at once. Imagine further that all these
programs have access to the same set of global variables and function calls. Each of these programs would
represent a thread of execution and is thus called a thread. The important differentiation is that each thread
does not have to wait for any other thread to proceed. All the threads proceed simultaneously. To use a
metaphor, they are like runners in a race, no runner waits for another runner. They all proceed at their own
rate.
Running Codes
class Thread
{
public:
Thread();
int Start(void * arg);
protected:
int Run(void * arg);
static void * EntryPoint(void*);
virtual void Setup();
virtual void Execute(void*);
void * Arg() const {return Arg_;}
void Arg(void* a){Arg_ = a;}
private:
THREADID ThreadId_;
void * Arg_;
};
Thread::Thread() {}
int Thread::Start(void * arg)
{
Arg(arg); // store user data
int code = thread_create(Thread::EntryPoint, this, & ThreadId_);
return code;
}
int Thread::Run(void * arg)
{
Setup();
Execute( arg );
}
/*static */
void * Thread::EntryPoint(void * pthis)
{
Thread * pt = (Thread*)pthis;
pthis−>Run( Arg() );
}
virtual void Thread::Setup()
{
// Do any setup here
}
virtual void Thread::Execute(void* arg)
{
// Your code goes here
}


The Tracing War Story in C++

Every software product we have ever worked on contained tracing functionality in one form or another.
Any time your source code exceeds a few thousand lines, tracing becomes essential. It is important for
debugging, maintaining, and understanding execution flow of nontrivial software. You would not expect a
trace discussion in a performance book but the reality is, on more than one occasion, we have run into
severe performance degradation due to poor implementations of tracing. Even slight inefficiencies can
have a dramatic effect on performance. The goal of this chapter is not necessarily to teach proper trace
implementation, but to use the trace vehicle to deliver some important performance principles that often
surface in C++ code. The implementation of trace functionality runs into typical C++ performance
obstacles, which makes it a good candidate for performan ce discussion. It is simple and familiar. We don't
have to drown you in a sea of irrelevant details in order to highlight the important issues. Yet, simple or
not, trace implementations drive home many performance issues that you are likely to encounter in any
random fragment of C++ code.
Many C++ programmers define a simple Trace class to print diagnostic information to a log file.
Programmers can define a Trace object in each function that they want to trace, and the Trace class can
write a message on function entry and function exit. The Trace objects will add extra execution overhead,
but they will help a programmer find problems without using a debugger. If your C++ code happens to be
embedded as native code in a Java program, using a Java debugger to trace your native code would be a
challenge.
The most extreme form of trace performance optimization would be to eliminate the performance cost
altogether by embedding trace calls inside #ifdef blocks:


Running Codes
#ifdef TRACE
Trace t("myFuction"); // Constructor takes a function name argument
t.debug("Some information message");
#endif
int myFunction(int x)
{
string name = "myFunction";
Trace t(name);
...
string moreInfo = "more interesting info";
t.debug(moreInfo);
...
}; // Trace destructor logs exit event to an output stream

class Trace {
public:
Trace (const string &name);
~Trace ();
void debug (const string &msg);

static bool traceIsActive;
private:
string theFunctionName;
};
inline
Trace::Trace(const string &name) : theFunctionName(name)
{
if (TraceIsActive) {
cout << "Enter function" << name << endl; } }
http://www.fortran-2000.com/ArnaudRecipes/CompilerTricks.html
http://www.pearsonhighered.com/educator/product/Efficient-C-Performance-Programming-Techniques/9780201379501.page