Thursday, September 25, 2014

Using Enumeration in C++

Enumeration in C++ is a user defined type that contains a set of constant values. An enumeration consists of an identifier and a list of types. Every type in an enumeration corresponds to a constant value. Default value for the first type is integer 0 and the next one gets the integer value 1. But an enumeration type can have a value other than default integer 0. Therefore an enum type can be casted to integer.


Following sample project created by qt creator and contains following files:
1- UsingEnumeration.pro
2- device.h
3- device.cpp
4- main.cpp



UsingEnumeration.pro file contains project configuration.

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += main.cpp \
    device.cpp
HEADERS += \
    device.h

device.h header file contains definition for Device class and Status enumeration.

#ifndef DEVICE_H
#define DEVICE_H

namespace UsingEnumsSample
{

enum Status {
    IDLE = 0,
    ACTIVE = 1,
    DEAD = 2
};

class Device
{
public:

    Device();
    void setStatus(Status pStatus);
    Status getStatus();

private:
    Status status;
};

}

#endif // DEVICE_H


device.cpp file contains implementation for Device class. setDevice method accepts an enumerator and assigns the passed value to Device class private enumeration member.

#include "device.h"

namespace UsingEnumsSample
{

Device::Device()
{
}

void Device::setStatus(Status pStatus)
{
    status = pStatus;
}

Status Device::getStatus()
{
    return status;
}

}

main.cpp method creates a Device instance and calls its setStatus and getStatus methods to set the Status value to the private Status enumeration member.

#include <iostream>
#include "device.h"

using namespace std;
using namespace UsingEnumsSample;

int main()
{
    Device device;
    device.setStatus(ACTIVE);
    cout << device.getStatus() << endl;
    device.setStatus(IDLE);
    cout << device.getStatus() << endl;
    return 0;
}

When the main method is executed, values of the Status member is displayed on the terminal which are consequently 1 and 0 as the program runs.

Wednesday, August 13, 2014

boost::array of std::string items in Qt Creator

boost::array is a template class which enables it to be able to be declared for different type of items. There exists an array as a member inside boost:array template class declaration so boost:array also acts a C-array wrapper with fixed number of items inside it.

Following sample project created by qt creator and contains following files:
1- BoostArrayOfStrings.pro
2- main.cpp



BoostArrayOfStrings.pro file contains project configuration.

TEMPLATE = app
CONFIG += console

SOURCES += main.cpp

INCLUDEPATH += /home/tufan/boost_1_55_0

Boost header files and libraries are located under the directory : /home/tufan/boost_1_55_0

main.cpp file contains main method.

#include <boost/array.hpp>
#include <string.h>

using namespace std;

int main()
{
    typedef boost::array<string,3> boostArray;
    boostArray stringArray;

    stringArray[0] = "FirstStringMember";
    stringArray.at(1) = "SecondStringMember";
    stringArray.at(2) = "ThirdStringMember";

    // some common container operations
    cout << "size:     " << stringArray.size() << endl;
    cout << "empty:    " << boolalpha << stringArray.empty() << endl;
    cout << "front:    " << stringArray.front() << endl;
    cout << "back:     " << stringArray.back() << endl;
    cout << "elements:    " << endl;

    for(boostArray::iterator iter(stringArray.begin()); iter != stringArray.end(); ++iter)
    {
        cout << *iter << endl;
    }

    return 0;
}
boost array contains 3 string items. Members of the array are initialized by using array subscript operator and at() function.

size:     3
empty:    false
front:    FirstStringMember
back:     ThirdStringMember
elements:  
FirstStringMember
SecondStringMember
ThirdStringMember

Tuesday, August 12, 2014

boost::array of Integers in Qt Creator

boost::array provides C-style array declaration and usage with constant number of items inside it. When only static-constant sized arrays are required, then boost::array comes with a better memory management solution than std::vector.

After including boost libraries into a Qt Creator C++ project, it becomes easy to use boost::array type of members in your programs.

boost/array.hpp file contains boost::array type.

As the boost::array documentation indicates boost::array is the STL compliant container wrapper for arrays of constant size.



Following sample project created by qt creator and contains following files:

1- BoostArrayOfIntegers.pro
2- main.cpp


BoostArrayOfIntegers.pro file contains project configuration.
TEMPLATE = app
CONFIG += console

SOURCES += main.cpp

INCLUDEPATH += /home/tufan/boost_1_55_0

I have installed the boost library to the directory         :  /home/tufan/boost_1_55_0
and boost/array.hpp file is located at                           :  /home/tufan/boost_1_55_0/boost/array.hpp

so qt creator does not complain about path related errors.


There is also another installed boost library which contains an older version of boost libraries  at directory : /usr/include/boost


In BoostArrayOfIntegers.pro file I have stated that I will use the boost library from specific location and qt creator selected the library from : /home/tufan/boost_1_55_0


main.cpp file contains main method.

#include <boost/array.hpp>

using namespace std;

int main()
{
    typedef boost::array<int, 4> intArrayType;
    intArrayType myArray = {{1,2,3,4}};
    std::cout << "boost intArray content :" << "\n";
    for( intArrayType::const_iterator iterator = myArray.begin(),
         iteratorEnd = myArray.end();
         iterator != iteratorEnd; ++iterator )
    {
        cout << *iterator << endl;
    }

    return 0;
}
boost::array is initialized with 4 integer members in curly braces. I used an iterator to traverse the integer members of the boost::array.

When the project is executed the following terminal output is generated :

boost intArray content :
1
2
3
4

Friday, August 1, 2014

Build Boost 1.55.0 C++ Libraries on Ubuntu

  Boost libraries are used by C++ programmers to increase the productivity of software product development process. Instead of reinventing the wheel, by using Boost libraries initial-development time costs are decreased remarkably.
  Boost libraries include many benefits for C++ programmers, such as shared_ptr, arrays, serialization, I/O etc. , which most of the time causes troubles. So it becomes crucial to invest time to learn Boost libraries for a C++ programmer to use these benefits and advantages.
  Most Linux distributions come with pre-installed Boost libraries. However, they do not always contain the latest version of Boost libraries.
  In order to build and start using on Ubuntu OS following steps can be followed :

1- download boost_1_55_0.zip file from
 
    http://sourceforge.net/projects/boost/files/boost/1.55.0/

2- unzip your downloaded boost_1_55_0.zip file

    $ unzip boost_1_55_0.zip

3- get required dependencies which are going to help you during build process
 
    $ sudo apt-get update
    $ sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev build-essential libbz2-dev

4- change your location into your unzipped boost_1_55_0 folder from terminal
 
    $ cd boost_1_55_0/

5- start bootstrapping

    $ ./bootstrap.sh --prefix=/usr/local

6- start building boost libraries

    $ sudo ./b2

7- after waiting for a time-period all the Boost libraries are built successfully.

    "The Boost C++ Libraries were successfully built!"

8- now Boost header files and libraries are ready for being used in your C++ applications.

Sunday, May 11, 2014

Throw and Catch Custom Exception Object in C++

Exceptions are run-time errors that occur during program execution. C++ Standard Library comes with a base class "exception" which is mainly dealing with exceptions. In some circumstances it is required to create-design your own custom exception classes in C++ as in other object oriented programming languages.
what() function of exception class of C++ Standard Library used to provide detailed information about the problem to the client program code in the case of an exception.

Following sample project created by qt creator and contains following files:
1- CustomException.pro
2- DequeWrapper.h
3- DequeWrapper.cpp
4- EmptyContainerException.h
5- EmptyContainerException.cpp
6- main.cpp

CustomException.pro file contains project configuration.

TARGET = CustomException
TEMPLATE = app
SOURCES += main.cpp \
           DequeWrapper.cpp \
           EmptyContainerException.cpp

HEADERS += \
           DequeWrapper.h \
           EmptyContainerException.h

main.cpp file contains main method and the usage of the EmptyContainerException exception instance.
#include "DequeWrapper.h"
#include <iostream>

using namespace std;
using namespace CustomContainers;

int main()
{
    try
    {
        DequeWrapper mDequeWrapper;
        mDequeWrapper.popBack();
    }
    catch(const EmptyContainerException& ex)
    {
        cerr << ex.what() << endl;
    }

    return 0;
}

DequeWrapper.h is the header file for the deque wrapper class declaration.
#ifndef DEQUEWRAPPER_H
#define DEQUEWRAPPER_H

#include <deque>
#include "EmptyContainerException.h"

namespace CustomContainers
{

class DequeWrapper
{
public:
    bool empty() const;
    int popBack();

protected:
    std::deque mDeque;
};

}
#endif // DEQUEWRAPPER_H

DequeWrapper.cpp is the implementation file for the deque wrapper header file.

#include "DequeWrapper.h"

namespace CustomContainers
{

bool DequeWrapper::empty() const
{
    return mDeque.empty();
}

int DequeWrapper::popBack()
{

    if(mDeque.empty())
        throw EmptyContainerException();

    int mItem(mDeque.back());
    mDeque.pop_back();
    return mItem;
}

}
EmptyContainerException.h file is the header file for the custom exception class declaration.
#ifndef EMPTYCONTAINEREXCEPTION_H
#define EMPTYCONTAINEREXCEPTION_H

#include <exception>

namespace CustomContainers
{

class EmptyContainerException : public std::exception
{
    public:
        virtual const char* what() const throw();
};

}

#endif // EMPTYCONTAINEREXCEPTION_H

EmptyContainerException.cpp file is the implementation file for the custom exception class header file.

#include "EmptyContainerException.h"

namespace CustomContainers
{

const char* EmptyContainerException::what() const throw()
{
    return "container is empty!";
}

}

std::exception what() method is reimplemented in the derived class EmptyContainerException to provide the description of the exception. When you run the above sample program main method following console output "container is empty" exception message is generated :