A case in point: We are working on the Darwin problem, which you can find more about here. This is, refreshingly, a problem which begs the OOP paradigm. So we made a Creature class to represent the different creatures in the world. Now the thing is, every Creature needs to have a reference to the Darwin world it belongs to. This is so that it can ask its world - "hey is there a wall ahead of me?" and other such useful questions. All of them need to have the same reference - so it's obvious that an externally created Darwin object must be passed to each Creature and stored as a const reference. However, in C++ you cannot initialize reference variables in the body of your constructor! And you definitely need to have it initialized since it's a reference variable, for crying out loud! Initialization lists come to the rescue. The initialization lists run before the constructors are called and can therefore initialize any member reference variables you may have declared.
That's not where the idiosyncrasies end. Have a static member variable in your class, do ya?! Well you can't initialize it in there. You MUST redeclare and intialize it outside the class in the form:
Type ClassName::staticMember = value;
Rather annoying!
An interesting list of other facts I learnt is:
- Local static variables get initialized only once and consequent initializations don't throw an error, they are simply ignored. Thus they can be considered as global variables as far as value is concerned, but with limited scope.
- If you have a statement globally, such as
int j = g(), theng()runs before main, so that j can be initialized. - You cannot have the same name for globals in 2 different C++ files unless one of them is static, which will make the global variable file-scoped.
- Uninitialized built-in local variables get initialized to garbage, global ones to 0.
- A static class variable in Java has just one copy across template flavors. Thus one cannot declare a static variable of the template type when defining the templated class. This, however is allowed in C++, since there is a copy per template flavor.
Well, this has definitely been an eye-opening experience for me. I hope I don't garbage-collect it all!