C++: Why prefer member initialization list over assignment?

The answer is simple – the latter could be a costly choice. I will try to explain this using a simple example. In the following program we have a class Bar that has a private data member of type Foo (another class). Now, lets say we want to create an object of type Bar initializing its data member with an object of type Foo, something like, Bar obj2(obj1); The following program defines the necessary functions to give an idea of what happens during the creation of such objects.

#include 

using namespace std;

class Foo {
public:
  Foo() { cout << "Foo: default ctor called." << endl; }
  Foo(const Foo &obj) { cout << "Foo: copy ctor called." << endl; }

  Foo & operator =(const Foo &obj)
  {
    cout << "Foo: overloaded assignment operator called." << endl;
    return *this;
  }

  ~Foo() { cout << "Foo: default dtor called." << endl; }
};

class Bar {
public:
  Bar() { cout << "Bar: default ctor called." << endl; }

  /* Parameterized constructor (without member initialization list) */
  Bar(Foo &foo)
  {
    cout << "Bar: ctor taking reference to Foo as param.." << endl;
    m_foo= foo;
  }

  ~Bar() { cout << "Bar: default dtor called." << endl; }

private:
  Foo m_foo;
};

int main()
{
  Foo obj1;
  Bar obj2(obj1);
  return 0;
}

Lets focus on Bar's parameterized constructor & how it affects the output.

..snip..

  /* Parameterized constructor (without member initialization list) */
  Bar(Foo &foo)
  {
    cout << "Bar: ctor taking reference to Foo as param.." << endl;
    m_foo= foo;                             /* Use assignment operator */
  }

..snip..

Output:
Foo: default ctor called.
Foo: default ctor called.
Bar: ctor taking reference to Foo as param..
Foo: overloaded assignment operator called.

Bar: default dtor called.
Foo: default dtor called.
Foo: default dtor called.

As we can see, while Bar's object is being constructed,

  1. Foo's default constructor is first invoked to construct the Foo's part of Bar, and then
  2. Foo's assignment operator is invoked to initialize it with the object supplied as parameter to this constructor.

Said that, let us now see how this can be improved by using member initialization list in Bar's parameterized constructor's definition.

..snip..

  /* Parameterized constructor (with member initialization list) */
  Bar(Foo &foo) : m_foo(foo)
  {
    cout << "Bar: ctor taking reference to Foo as param.." << endl;
  }

..snip..

Output:
Foo: default ctor called.
Foo: copy ctor called.
Bar: ctor taking reference to Foo as param..

Bar: default dtor called.
Foo: default dtor called.
Foo: default dtor called.

Looking at the above output, we can see that during the construction of Bar's object, Foo is being constructed & initialized directly by Foo's copy constructor, instead of using the default constructor to create an uninitialized object followed by the assignment operator.

Hence using member initialization list, one can completely avoid the use for overloaded assignment operator and thus save some precious CPU clocks.

Compile time assertion

So, what is an assertion? According to gnu.org :

Its a statement in a program that a condition is true at this point in the program. Useful for reasoning about how a program is supposed to behave.

That is – assertions are predicates (or expressions that result in true/false) that programmers add at various places in the code to convey that the specified conditions must be true for the program to continue & execute normally. Assertions can be used to state the precondition – a condition that must hold true before the execution enters a particular code fragment, or postcondition – a condition that must hold true after the execution of a particular code fragment that it follows. These checks would help in early detection of a problem, which might become tricky to detect otherwise.

Assertions mostly work at either compilation time or execution time. While an assertion failure at execution time can abort a running process (in order to avoid a potential catastrophe), the assertion at compile time would cause the build (compilation) itself to fail. Both have their own advantages. Runtime assertions are widely used in C/C++ programs using assert macro. They are checked during the program execution and in case of assertion failure a signal is raised to abort the program. On the other hand compile-time assertions (the subject of this article) work during compilation phase, failure of which results in termination of compilation.

The predicate in compile-time assertion is normally an expression around compile-time constants. They are usually pre-processor macros that inject syntactically invalid code in the program in case of predicate failure & hence the compilation fails.

Lets understand this by taking an example from MySQL code :

In case the expression – expr – evaluates to false, the above macro would create a character array of an invalid size (-1) which would terminate the compilation. Also note that compilation error like ‘redeclaration error’ can be avoided as the array is defined within a do-while loop, opening up the possibility of it being used at multiple places even inside a function or block.

compile_time_assert(sizeof (some_struct) == 12); // sizeof is a compile-time operator.

C11/C++11 standards have added support for compile-time assertions aka ‘static assertions’ by introducing a new keyword static_assert:

static_assert (constant-expression, error-message);
...
  static_assert(sizeof (int) == 8, "A deliberate static assertion..");
..

$ g++ -std=c++0x static_assert.cpp 
static_assert.cpp: In function ‘int main()’:
static_assert.cpp:3:3: error: static assertion failed: "A deliberate static assertion.."

P.S. Here I intentionally omitted an important preprocessor directive #error which can be used to define assertions during preprocessing stage.

A quick take on ClassNotFoundException: com.mysql.jdbc.Driver

Its a common problem that programmers often face and sometimes look for a solution. The problem is clear – JVM is not able to locate the MySQL JDBC driver. We will try to solve this step-by-step using a simple java program (below) to print server’s version information. Also, before we proceed please note that I will be trying it on my Ubuntu laptop where I already have got java (openjdk) and MySQL Connector/J (libmysql-java) installed.

Now lets try to compile & run it.

$ javac Version.java 
$ java Version 
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

As expected, jvm is not able to locate the driver jar. We can easily fix this by setting the CLASSPATH environment variable to point to the MySQL Connector/J jar file (mysql-connector-java-5.1.10.jar) on the system.

$ export CLASSPATH=/usr/share/java/mysql-connector-java-5.1.10.jar:.
$ java Version 
5.7.2-m12-debug-log

One last thing to note here is that we have also appended ‘.‘ (i.e. the current directory) to the CLASSPATH in order to be sure that our main ‘Version’ class can also be found.

Problem#1 : Multiply two numbers specified as strings

/**
  A function that multiplies two positive integer numbers stored as strings.

  @Assumptions:
    1) This program does not handle negative numbers. Not even +/- signs.
    2) It will not prune down leading 0's.
    3) The two input strings consist of valid digits only.

  @Algorithm:
    0) Create a result string of size (a.length + b.length).
    1) Take the last untouched digit (least-significant to start with) of one of
       the given numbers (in this case I picked 'b').
    2) Multiply it with all the digits of the other number ('a').
    3) Accumulate the outcome in the result string.
    4) Goto step 1.

*/

#include 

#define INT(c)  ((int)((c) - '0'))
#define CHAR(i) ((char)(i + int('0')))

using namespace std;

string multiply(const string &a, const string &b)
{
  /* initially fill the result string with 0's */
  size_t total_len= a.length() + b.length();
  string result(total_len, '0');

  int num;                                      /* intermediate store */
  int i, j;
  int last_pos_i, last_pos_j, last_pos_k;

  last_pos_i= total_len - 1;

  /* i-loop */
  for (i= b.length() - 1; i >= 0; i --)
  {
    last_pos_j= last_pos_i;

    /* j-loop */
    for (j= a.length() - 1; j >=0; j --)
    {
      last_pos_k= last_pos_j;
      num= INT(a.at(j)) * INT(b.at(i));

      /* k-loop : the actual updation of result string takes place here. */
      while (num)
      {
        num += INT(result.at(last_pos_k));
        result.at(last_pos_k)= CHAR(num % 10);
        /* 'carry' it forward.. ;) */
        num= num / 10;
        last_pos_k --;
      }

      last_pos_j --;
    }

    last_pos_i --;
  }
  return result;
}

int main()
{
  string n1("99");
  string n2("9");
  cout << n1 << " * " << n2 << " = "  << multiply(n1, n2) << endl;
  return 0;
}

Output:

> ./a.out 
99 * 9 = 891

Building a MySQL client program on Linux

Building a C program (client) to connect to MySQL server is simple, but at times it can become a little problematic for a newbie to find all the necessary dependencies (includes/libs). The best option that I would recommend is to use the mysql_config script that comes bundled with the MySQL distribution. This shell script when executed with some options, would print all necessary compiler options/flags/switches required to build a MySQL client program. Lets see it in action!

/**
  @file client_version.c
  Display the client version.
*/

#include 
#include                               /* All public MySQL APIs */

int main()
{
    printf("MySQL client version: %s\n", mysql_get_client_info());
    return 0;
}

# mysql_config's output
> .../bin/mysql_config --cflags --libs
-I/path..to../include  -fPIC -g -fabi-version=2 -fno-omit-frame-pointer -fno-strict-aliasing
-L/path..to../lib -lmysqlclient -lpthread -lm -lrt -ldl

# and now pass it down to the compiler..
> gcc client_version.c `/home/nirbhay/project/repo/bld/trunk/bld/bin/mysql_config --cflags --libs`
.. done

> ./a.out 
MySQL client version: 5.7.2-m12

# whoa.. that worked!

Sometimes, the generated binary would complain of missing shared object file. It can be solved by setting up LD_LIBRARY_PATH to the lib directory containing libmysqlclient.so.NN file.

> ./a.out 
./a.out: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object file: No such file or directory
nirbhay@Nirbhay-lenovo:~/project/sandbox/mysql$ ldd a.out 
	linux-vdso.so.1 =>  (0x00007fffce1ee000)
	libmysqlclient.so.18 => not found
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fca652e6000)
	/lib64/ld-linux-x86-64.so.2 (0x00007fca656a3000)

LD_LIBRARY_PATH=/path..to../lib ./a.out
MySQL client version: 5.7.2-m12

Producer/consumer using pthreads

Here I present a C-program to demonstrate the use of pthreads to solve the classical producer/consumer problem. The following (self-explaining) program makes use of pthread’s mutex & condition APIs to achieve synchronization between producer & consumer threads. The program implements a simplified version of the original problem : the producer increments (produces) an integer, a shared resource, while the consumer prints (consumes) it.

Output:

Consumer : "Hello I am consumer #140317330908928. Ready to consume numbers now"
Producer : "Hello I am producer #140317322516224. Ready to produce numbers now"
Producer : 1
Consumer : 1
Producer : 2
Consumer : 2
Producer : 3
Consumer : 3
Producer : 4
Consumer : 4
Producer : 5
Consumer : 5
Producer : 6
Consumer : 6
Producer : 7
Consumer : 7
Producer : 8
Consumer : 8
Producer : 9
Consumer : 9
Producer : 10
Producer done.. !!
Consumer : 10
Consumer done.. !!
Done..