A Developer's Diary

Jul 19, 2010

C++ Idioms - Non Copyable Objects

The Non Copyable idiom in C++ allows us to create classes whose objects cannot be constructed using a copy constructor or assigned to another. Some of the classes using this idiom provide mutually exclusive access to the resources e.g. Mutex, Semaphores, Document, Memory, File etc

Key Idea
To prevent objects of a class from being copy constructed or assigned to each other, declare the copy constructor and the assignment operator as private and do not provide implementations
//File: NonCopyable.h
#include <iostream>

class NonCopyable
{
protected:
    NonCopyable(){}
    ~NonCopyable(){}

private:
    //Restrict the copy constructor
    NonCopyable(const NonCopyable&);
    //Restrict the assignment operator
    NonCopyable& operator=(const NonCopyable&);
};

Read more ...

Jul 18, 2010

Static Member Functions

A static member function can be accessed using an instance variable or using the class name. It is better to use class name to access a static method as it is more readable and speaks by itself that the method being called is a static member

//File: static_example.h
#include <iostream>
using namespace std;

class StaticExample
{
    public:
        StaticExample();
       ~StaticExample();

        //static member function
        static int StaticMethod();

    private:
        StaticExample(const StaticExample&);
        StaticExample& operator=(const StaticExample&);

        std::string m_str;
};

//File: static_example.cpp
#include "static_example.h"

StaticExample::StaticExample()
{
}

StaticExample::~StaticExample()
{
}

int StaticExample::StaticMethod()
{
    cout << "static method called";
    cout << endl;
    return 0;
}

Read more ...

Jul 17, 2010

Conditional execution in ant

An ant target can be configured to execute conditionally using if and unless attributes available.
A simple ant target without any attributes

<project name="examples" default="simple_target_example">

  <target name="simple_target_example">
    <echo message="a simple target example"/>
  </target>

</project>
Output
$ ant
Buildfile: build.xml

simple_target_example:
     [echo] a simple target example

BUILD SUCCESSFUL
Total time: 0 seconds

Ant target with an if attribute
<project name="examples" default="example_if_target">

  <target name="property_target">
    <property name="greetings" value="1"/>
  </target>

  <target name="example_if_target" depends="property_target" if="greetings">
    <echo message="Greetings"/>
  </target>

</project>
Output
$ ant
Buildfile: build.xml

property_target:

example_if_target:
[echo] Greetings

BUILD SUCCESSFUL
Total time: 0 seconds

The if="greetings" attribute causes the target to be executed if greetings property is set and the unless="greetings" attribute causes the target to be executed only if the property greetings is not set

Ant target with an unless attribute
<project name="examples" default="example_unless_target">

  <target name="example_unless_target" unless="greetings">
    <echo message="Greetings"/>
  </target>

</project>
Output
$ ant
Buildfile: build.xml

example_unless_target:
[echo] Greetings

BUILD SUCCESSFUL
Total time: 0 seconds


//setting the greetings property
Output
$ ant -Dgreetings=1
Buildfile: build.xml
 

example_unless_target:
BUILD SUCCESSFUL
Total time: 0 seconds

Read more ...

Jul 10, 2010

Standard Template Library - pair

The pair class template declared in <utility> is provided to treat two values as a single unit. STL container classes map and multimap use pairs to manage their elements which are key/value pairs

The example code below demonstrates some of the ways of using a pair class and the convenience function make_pair()

#include <utility>
#include <iostream>
#include <string>
#include <map>

using namespace std;

void print_pair(pair<long, string> pr)
{
    cout << "[";
    cout << pr.first;
    cout << "]";
    cout << "=";
    cout << pr.second;
    cout << endl;
}


// Example: simple pair example
void simple_pair_example()
{
    pair<long, string> pr(1, "Simple Pair");
    print_pair(pr);
    cout << endl;
}

// Example: pointer to a pair
void pair_pointer_example()
{
    pair<long, string> *pr = new pair<long, string>(1, "Pointer Pair");
    print_pair(*pr);
    cout << endl;
    delete pr;
    pr = NULL;
}


// Example: pair and a map
void pair_map_example()
{
    map<long, string>   employees;

    employees[1] = "Employee1";
    employees[2] = "Employee2";
    employees[3] = "Employee3";
    employees[4] = "Employee4";

    map<long, string>::const_iterator it;
    for(it = employees.begin(); it != employees.end(); ++it)
    {
        print_pair(*it);
    }
    cout << endl;
}


// Example: pair and map find function
void pair_map_search()
{
    string user = "george";
    map<string, pair<string, string> >   employees;

    employees["pankaj"] = make_pair("Pankaj", "Tiwari");
    employees["paresh"] = make_pair("Paresh", "Tiwari");
    employees["george"] = make_pair("George", "Bush");

    map<string, pair<string, string> >::const_iterator it;
    if((it = employees.find(user)) == employees.end())
    {
        cerr << "Unknown User: " << user;
    }
    else
    {
        const pair<string, string> user = it->second;
        cout << user.first << user.second;
    }
    cout << endl;
}

int main()
{
    simple_pair_example();
    pair_pointer_example();
    pair_map_example();
    pair_map_search();
}


Read more ...

Jul 5, 2010

Integer to Binary Representation

Binary representation is a number written using base 2. Each digit can have only one of the two possible values (0 or 1) e.g. 255 is written as 00000000 00000000 00000000 11111111, 500 as 00000000 00000000 00000001 11110100 and 1024 as 00000000 00000000 00000100 00000000

The following program converts an entered integer to it's equivalent binary representation

#include <stdio.h>
#define SIZE 8*sizeof(int)

int int2bin(int, char*);
int print_bstr(const char*);
int error();

int main()
{
    int number;
    char bstr[SIZE];
    while(1){
        printf("\nEnter the number ");
        scanf("%d", &number) ? int2bin(number, bstr) : error();
        print_bstr(bstr);
    }
}

int int2bin(int num, char* bstr)
{
    int i;
    for(i = SIZE - 1; i >= 0 ; --i, num >>= 1)
    {
        bstr[i] = (0x1 & num) + '0';
    }

    bstr[SIZE] = '\0';
}

int print_bstr(const char* bstr)
{
    int i = 0;
    while(bstr[i])
    {
        putchar(bstr[i++]);
        if(i % 8 == 0  && bstr[i])
            putchar(' ');
    }
}

int error()
{
    printf("Error: non-numeric data entered. Exiting");
    exit(-1);
}


Read more ...

Jul 1, 2010

Extended ASCII Character Set


The following is a simple program which prints the characters of an extended ASCII character set

Read more ...