Archive for April, 2013


Unusual C++ use of #include

Muhamad Hesham's T-Blog


The usual use is to write it at the very top of your .h/.cpp files to include other header files like (Windows.h, iostream, cstdio, etc..) to use the what is defined inside in your .h/.cpp file.

The unusual use is to use it to initialize a data-structure like arrays by including a text file that contains the array initialization data between the array initializer list parentheses – e.g XX XXX[] = { <HERE> }. This is is illustrated in the sample program below. The same concept can be used to initialize an array of any dimension.

// main.cpp
#include <cstdio>
#include <Windows.h>

struct Person
    char        *pName;
    unsigned    Age;
    unsigned    Height;
    char        Gender;

// Declare and initialize a 1D array of Persons structs using PersonTableData text file
// #include "PersonsTableData" will be expanded at COMPILE TIME to the content of PersonsTableData file
Person PersonsTable[] = {
    #include "PersonsTableData"

View original post 73 more words


Resource Acquisition is Initialization (RAII)

This post will be about the Resource Acquisition is Initialization (RAII) pattern which is a creational pattern. This is going to be the first non Gang of Four pattern I will write about.

The Purpose

The idea behind this pattern is to correctly dispose of all the resources that you acquire. This pattern was first written about by Bjarne Stroustrup, the creator of C++. The most common examples of this pattern are in opening and closing files and web sockets. It is also important in controlling mutexes so you can write tread safe code.

Continue reading ‘Resource Acquisition is Initialization (RAII)’


Comparisons in C++

This is about the comparison operators in C++ and making them easy to implement. There are 6 comparison operators in C++; ==, !=, <, <=, >, and >=. If you want to be able to apply all of these to a class, and you have the right type of order, you only need to implement one function which will determines them all. Incidentally this is called a total order, but I won’t go into what that means here.

The tl;dr of this is look at this repository and use a class from there to easily implement custom comparison operators.

This idea is to map the order onto the real numbers (doubles). So you have a function which takes two instances of a class and returns a double. If this function returns a negative number then the first instance is less than the second, if it returns 0 they are equal and if it returns a positive number then the first instance is greater than the second.

This will be easier to see with an example, so here is a class which is just data storage for an int.

Continue reading ‘Comparisons in C++’