Sunday, April 26, 2009

A few C++ Quirks

It's very usual in Java to initialize something which is constant throughout the class as static const within the class definition in the following way:

private static final String MAX_THREADS = 5;

After coding in Java for BlackBerry development for a few months, when I started working with C++ Qt framework, I did it in the same manner:

static const QString TITLE_TEXT = "Title Text";

I got the error - only static const integral data members can be initialized within a class. Google led me to the following solution:

1) declare in header file - static const QString TITLE_TEXT;
2) initialize in cpp file - const QString ClassName::TITLE_TEXT = "Title Text";

In the second step, I tried prepending static but got error - 'static ' storage-class specifier illegal on members.

In Java, the mechanism of indirection for constructors is as simple as calling this() with necessary arguments. We often do this to keep the initialization code in only one place. In C++, when tried, I got the error - term does not evaluate to a function taking 3 arguments. When I replaced this with a custom function initialize() where all the initialization code were put together, it worked fine.

Working with multiple languages sometimes does give trouble :-(