Wednesday, 17 June 2009

Initialising Arrays while doing 'new'

The example below shows how to initialise the array when you are dynamically alocating the memory with new:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

//int* x = new int(10); - Common Bug for Array allocation
int *x = new int[5]; // Memory UnInitialised
int *y = new int[5]();

for
(int i = 0; i < 5; i++)
{

cout<<"x["<<i<<"]="<<x[0]<<endl;
cout<<"y["<<i<<"]="<<y[0]<<endl;
}


//delete x; - Another Common bug
delete[] x;
delete
[] y;
return
0;
}



The output is as follows:

Monday, 15 June 2009

Avoiding Redifinition using #pragma once

Lets write a very simple program where there is main.cpp that includes classA.h and classB.h. classA.h contains class A and classB.h contains class B.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to show how to avoid redifinition problems
#include <iostream>
#include "classA.h"
#include "classB.h"

using namespace
std;

int
main()
{

A a;
B b;
a.a = 20; //some stuff not relevant here
b.a = 40; //some stuff not relevant here
return 0;
}

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A very simple example class that does nothing
class A
{

public
:
int
a;
int
b;
private
:
int
c;
};
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A very simple example class that does nothing
#include "classA.h"

class
B :public A
{

private
:
int
d;
};

When we try to compile this, the compiler complains as follows:




To get round this problem, in each of the include file we can use a #define as follows

#ifndef _CLASSA_H_

#define _CLASSA_H

//Some code

#endif //_CLASSA_H

In C++ we can also write #pragma once. Using #pragma once can increase compilation speed and the compilor may optimise the code as the use of pre-processor can be removed. So the class A in our program giving problem can now be modified as follows for the program to compile properly:




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A very simple example class that does nothing
#pragma once
class A
{

public
:
int
a;
int
b;
private
:
int
c;
};


Wednesday, 10 June 2009

What can you do in C++ which you cant do in C

Is there anything you can do in C++ that you cannot do in C?

No. There is nothing you can do in C++ that you cannot do in C. After all you can write a C++ compiler in C.

Difference between MyClass p; and MyClass p();

Sometimes there are interesting questions asken in an interview. I am going to add some of them when I come across under the 'Interview Questions' tag.

So, what is the difference between MyClass p; and MyClass p();?

MyClass p; creates an instance of class MyClass by calling a constructor for MyClass.

MyClass p(); declares function p which takes no parameters and returns an object of class MyClass by value.

Monday, 8 June 2009

The problem with Maps in C++

The following discussion is from More Exceptional C++ By Herb Sutter:

Question 1:
a: What's wrong with the following code? How would you correct it?

map::iterator i = m.find( 13 );
if( i != m.end() )
{
const_cast( i->first ) = 9999999;
}

b: To what extent are the problems fixed by writing the following instead?

map::iterator i = m.find( 13 );
if( i != m.end() )
{
string s = i->second;
m.erase( i );
m.insert( make_pair( 9999999, s ) );
}

Consider a map named m that has the contents shown in Figure; each node within m is shown as a pair. I'm showing the internal structure as a binary tree because this is what all current standard library implementations actually use.

As the keys are inserted, the tree's structure is maintained and balanced such that a normal inorder traversal visits the keys in the usual less ordering. So far, so good.

But now say that, through an iterator, we could arbitrarily change the second entry's key, using code that looks something like the following:

1. a) What's wrong with the following code? How would you correct it?

// Example: Wrong way to change a

// key in a map m.

//

map::iterator i = m.find( 13 );

if( i != m.end() )

{

const_cast( i->first ) = 9999999; // oops!

}

Note that we have to cast away const to get this code to compile. The problem here is that the code interferes with the map's internal representation by changing the map's internals in a way that the map isn't expecting and can't deal with.

Example above corrupts the map's internal structure (see Figure). Now, for example, an iterator traversal will not return the contents of the map in key order, as it should. For example, a search for key 144 will probably fail, even though the key exists in the map. In general, the container is no longer in a consistent or usable state. Note that it is not feasible to require the map to automatically defend itself against such illicit usage, because it can't even detect this kind of change when it occurs. In Example above, the change was made through a reference into the container, without calling any map member functions.

A better, but still insufficient, solution is to follow this discipline: To change a key, remove it and reinsert it. For example:

b) To what extent are the problems fixed by writing the following instead?

// Example: Better way to change a key

// in a map m.

//

map::iterator i = m.find( 13 );

if( i != m.end() )

{

string s = i->second;

m.erase( i );

m.insert( make_pair( 9999999, s ) ); // OK

}

This is better, because it avoids any change to keys, even keys with mutable members that are significant in the ordering. It even works with our specific example. So this must be the solution, right?

Unfortunately, it's still not enough in the general case, because keys can still be changed while they are in the container. "What?" one might ask. "How can keys be changed while they're in the container, if we adopt the discipline of never changing key objects directly?" Here are two counterexamples:

Let's say the Key type has some externally available state that other code can get at—for example, a pointer to a shared buffer that can be modified by other parts of the system without going through the Key object. Let's also say that that externally available state participates in the comparison performed by Compare. Then making a change in the externally available state, even without the knowledge of the Key object and without the knowledge of the code that uses the associative container, can still change the relative ordering of keys. So in this case, even if the code owning the container tries to follow an erase-then-reinsert discipline, a key ordering change can happen at any time somewhere else and therefore without an erase-then-reinsert operation.

Consider a Key type of string and a Compare type that interprets the key as a file name and compares the contents of the files. It's obvious that even if the keys are never changed, the relative ordering of keys can still change if the files are modified by another process, or (if the file is shared on a network) even by a user on a different machine on the other side of the world.

For details see Item 8 of the book More Exceptional C++ By Herb Sutter



Monday, 1 June 2009

A look at Smart Pointers

There is lot of confucion, misconceptions and misunderstanding regarding smart pointers. After looking at various books and tutorials, i got quite confused till I managed to figure out what they exactly are:

Smart pointers are objects that look and feel like pointers, but are smarter.

To look and feel like pointers, smart pointers need to have the same interface that pointers do: they need to support pointer operations like dereferencing (operator *) and indirection (operator ->). An object that looks and feels like something else is called a proxy object, or just proxy.

To be smarter than regular pointers, smart pointers need to do things that regular pointers don't. What could these things be? Probably the most common bugs in C++ (and C) are related to pointers and memory management: dangling pointers, memory leaks, allocation failures and other joys. Having a smart pointer take care of these things.

The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library. You can find it in the header , or take a look at Scott Meyers' auto_ptr implementation. Here is part of auto_ptr's implementation, to illustrate what it does:

template <class T> class auto_ptr
{

T* ptr;
public
:
explicit
auto_ptr(T* p = 0) : ptr(p) {}
~
auto_ptr() {delete ptr;}
T& operator*() {return *ptr;}
T* operator->() {return ptr;}
// ...
};

As you can see, auto_ptr is a simple wrapper around a regular pointer. It forwards all meaningful operations to this pointer (dereferencing and indirection). Its smartness in the destructor: the destructor takes care of deleting the pointer.

Lets look at a proper example:

#include<iostream>
#include<memory>


using namespace
std;

class
A
{

public
:
int
*data;
string name;
A(string n): name(n)
{

cout<<"Constructor of A = "<<name.c_str()<<" called "<<endl;
data = new(int);
};

A(string n, int x): name(n)
{

cout<<"Overloaded Constructor of A = "<<name.c_str()<<" called "<<endl;
data = new(int);
*
data = x;
};
~
A()
{

cout<<"Destructor of A = "<<name.c_str()<<" called "<<endl;
delete
(data);
data = this->data;
data = NULL;
}

A* operator ->() { return this;};
};


void
someFunc()
{

auto_ptr<A> a1(new A("a1"));
cout<<"Enter a number and press enter: ";
cin >> (*a1->data);
cout << "a1->data = "<<*a1->data<<endl;

A a2("a2",25);
A *a3 = new A("a3");
}


int
main()
{

cout<<"Before SomeFunc()"<<endl;
someFunc();
cout<<"After SomeFunc()"<<endl;
return
0;
}
The output is as follows:


As you have probably noticed, the instance a3 is never deleted and will cause memory leaks. Using smart pointer would automatically delete the instance a3 and the memory associated with it.

You can read Smart Pointers in much more detail at the References below.

References:
http://ootips.org/yonat/4dev/smart-pointers.html
http://www.geekpedia.com/tutorial47_Smart-Pointers---Part-1.html
http://www.geekpedia.com/tutorial59_Smart-Pointers---Part-II.html

Monday, 25 May 2009

Thread Synchronization with Events

Here is an example of using Event with multiple threads for Thread Sync.

Event.h

//Example from http://www.relisoft.com/Win32/active.html
#if !defined _EVENT_H_
#define _EVENT_H_

class
Event
{

public
:
Event ()
{

// start in non-signaled state (red light)
// auto reset after every Wait
_handle = CreateEvent (0, FALSE, FALSE, 0);
}

~
Event ()
{

CloseHandle (_handle);
}


// put into signaled state
void Release () { SetEvent (_handle); }
void
Wait ()
{

// Wait until event is in signaled (green) state
WaitForSingleObject (_handle, INFINITE);
}

operator
HANDLE () { return _handle; }

private
:
HANDLE _handle;
};


#endif



Thread.cpp

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This shows example of Multithreading, thread sync, Events
#include <windows.h>
#include <process.h>
#include <iostream>
#include "Event.h"

using namespace
std;

void
Func1(void *);
void
Func2(void *);

Event _event; //Create an event

int
main()
{

HANDLE hThreads[2];

//Create two threads and start them
hThreads[0] = (HANDLE)_beginthread(Func1, 0, NULL);
hThreads[1] = (HANDLE)_beginthread(Func2, 0, NULL);

//Makes sure that both the threads have finished before going further
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);

cout << "Main exit" << endl;
return
0;
}


void
Func1(void *P)
{

int
Count = 0;

for
(;;)
{

_event.Wait();
do
//This loop will only start when Event is triggered
{
cout<<"Func1: Count = "<<Count++<<endl;
}
while(Count < 10);
return
;
}


return
;
}


void
Func2(void *P)
{

for
(int i = 0; i < 10; i++)
{

cout<<"Func2: i = "<<i<<endl;
}

//Release the event so Thread1 (Func1) can start
_event.Release();
return
;
}




You can also have a look at this example here which uses Event, Mutex, etc.

The output is as follows:

Monday, 18 May 2009

Avoiding Temporary Objects

I was trying to find something in this very interesting book, titled "Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions" by Herb Sutter.

There was a chapter called "Temporary Objects". Curiosity got the better of me and I started reading. The book is extremely well written and the problem very well explained. Here is a summary of the Temporary Objects problem. Have a look at the book for complete details.

Consider the following peice of code:


string FindAddr( list<Employee> emps, string name )
{

for
( list<Employee>::iterator i = emps.begin();
i != emps.end();
i++ )
{

if
( *i == name )
{

return
i->addr;
}
}

return
"";
}

This short function has three unnecessary temporary objects, two subtler ones, and two red herrings.

The two more-obvious temporaries are buried in the function declaration itself:

string FindAddr( list emps, string name )

The parameters should be passed by const reference (const&) instead of by value. So they would now become const list& and const string&, respectively. Pass-by-value forces the compiler to make complete copies of both objects, which can be expensive and completely unnecessary.

The third more-obvious avoidable temporary occurs in the for loop's termination condition:

for( /*...*/ ; i != emps.end(); /*...*/ )

For most containers (including list), calling end() returns a temporary object that must be constructed and destroyed. Because the value will not change, recomputing (and reconstructing and redestroying) it on every loop iteration is both needlessly inefficient and unaesthetic. The value should be computed only once, stored in a local object, and reused.

Next, lets consider the way we increment i in the for loop:

for( /*...*/ ; i++

Postincrement is usually less efficient than preincrement because it has to remember and return its original value. An example of Postincrement implementation is as follows:


const T T::operator++(int)
{

T old( *this ); // remember our original value
++*this; // always implement postincrement
// in terms of preincrement
return old; // return our original value
}
As you can see postincrement is less efficient than preincrement. Postincrement has to do all the same work as preincrement, but in addition it also has to construct and return another object containing the original value. Since the original value is never used in the code, there is no reason to use postincrement. Preincrement should be used instead.

You can continue reading this further in chapter 6 of the book. Book details as follows:


Monday, 11 May 2009

Another Multi-Threading example with Mutex

Here is an example where we combine the previous programs to create a multi-threaded mutex based program. If you havent already seen, then please check out the Singleton class and Multi-Threading with Thread Sync.

We are going to have some .h files in this example.

Lock.h

//Example from http://www.relisoft.com/Win32/active.html
#if !defined _LOCK_H_
#define _LOCK_H_

#include "Mutex.h"

class
Lock
{

public
:
// Acquire the state of the semaphore
Lock ( Mutex & mutex )
:
_mutex(mutex)
{

_mutex.Acquire();
}

// Release the state of the semaphore
~Lock ()
{

_mutex.Release();
}

private
:
Mutex & _mutex;
};


#endif



Mutex.h

//Example from http://www.relisoft.com/Win32/active.html
#if !defined _MUTEX_H_
#define _MUTEX_H_

class
Mutex
{

friend class
Lock;
public
:
Mutex () { InitializeCriticalSection (& _critSection); }
~
Mutex () { DeleteCriticalSection (& _critSection); }
private
:
void
Acquire ()
{

EnterCriticalSection (& _critSection);
}

void
Release ()
{

LeaveCriticalSection (& _critSection);
}


CRITICAL_SECTION _critSection;
};


#endif



Singleton.h

#include "Lock.h"
#include "Mutex.h"

class
aSingletonClass
{

public
:
//method to get Instance of class
static aSingletonClass *getInstance( void )
{

//Note that the class is only created when this method is called first time
if(!instance_)
instance_ = new aSingletonClass;
return
instance_;
}

//method to delete Instance of class
static void deleteInstance( void )
{

if
(instance_)
delete
instance_;
instance_ = NULL; //important as this can create dead reference problems
}
void
printSomething(char *name, int count)
{

Lock guard(mutex_);
std::cout << name << " loop " << count << std::endl;
}


private
:
//variable to store the instance of singleton
static aSingletonClass *instance_;
//default constructor should be private to prevent instantiation
aSingletonClass() {};
//destructor should be made private so no one can delete this accidently
~aSingletonClass() {};
//We also need to prevent copy being created of the object
aSingletonClass(const aSingletonClass&);

Mutex mutex_;
};



Thread.cpp

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This shows example of Multithreading, thread sync, Mutex
#include <windows.h>
#include <process.h>
#include <iostream>
#include "Singleton.h"

using namespace
std;

aSingletonClass* aSingletonClass::instance_ = NULL;

void
Func1(void *);
void
Func2(void *);

int
main()
{

HANDLE hThreads[2];

aSingletonClass *someVar = NULL;
//Create Instance
someVar = aSingletonClass::getInstance();

//Create two threads and start them
hThreads[0] = (HANDLE)_beginthread(Func1, 0, NULL);
hThreads[1] = (HANDLE)_beginthread(Func2, 0, NULL);

//Makes sure that both the threads have finished before going further
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);

cout << "Main exit" << endl;
return
0;
}


void
Func1(void *P)
{

int
Count;

for
(Count = 1; Count < 11; Count++)
{

aSingletonClass::getInstance()->printSomething("Func1", Count);
}

return
;
}


void
Func2(void *P)
{

int
Count;

for
(Count = 10; Count > 0; Count--)
{

aSingletonClass::getInstance()->printSomething("Func2", Count);
}

return
;
}





The Output is as follows:

Tuesday, 5 May 2009

An example of Interface class

Sometimes it is simple and helpful to define a class that does nothing but defines a standardised interface that can be used by other classes to make sure the implementation follows a standard set of input and output paramaters. Also this approach results in faster code runs and more maintainable code.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows an example of Interface class

#include<iostream>

using namespace
std;

//Shape is an Interface Class. No data and everything pure virtual
class Shape {
public
:
virtual
void Area(int length, int breadth) = 0;
virtual
void Perimeter(int length, int breadth) = 0;
//Note, no data
};

//Derived class - Inherits Shape as Public
class Rectangle : public Shape {
public
:
void
Area(int length, int breadth);
void
Perimeter(int length, int breadth);
private
:
int
someData;
};


//Derived class - Inherits Shape as Public
class Triangle : public Shape {
public
:
void
Area(int length, int breadth);
void
Perimeter(int length, int breadth);
private
:
int
someData;
};


int
main()
{

Rectangle r;
Triangle t;

cout<<"\n\n";
r.Area(3,4);
r.Perimeter(3,4);

t.Area(3,4);
t.Perimeter(3,4);

cout<<"\n\n";
return
0;
}


void
Rectangle::Area(int length, int breadth)
{

cout<<"\nThe Area of Rectangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)<<endl;
}


void
Rectangle::Perimeter(int length, int breadth)
{

cout<<"\nThe Perimeter of Rectangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<2 * (length + breadth)<<endl;
}


void
Triangle::Area(int length, int breadth)
{

cout<<"\nThe Area of Triangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)/2<<endl;
}


void
Triangle::Perimeter(int length, int breadth)
{

cout<<"\nThe Perimeter of Triangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)/3<<endl;
}


In the above example, Shape class is an 'abstract class'. All the interfaces are 'pure interfaces'. It contains no data. The derived classes now have to define the interace functions.

The output is as follows: