I’ve gone on and on before about how much I like Objective-C and especially, how well it plays with C++. Mixing the two is a pleasure, and it’s often hard to remember where one stops and the other one starts. So much so that sometimes I catch myself calling C++ member functions like this [self myFunction:param];. Oops.

It is true that Objective-C can be a bit more verbose than plain C++, but it more than makes up for it with named parameters (which increase readability a huge amount), and not having to duplicate many things between header and implementation files.

Yet, even though I like Objective-C so much, there was one last, really annoying feature that was preventing perfect interop between C++ and Objective-C. Something so simple, yet so fundamental, that it really got in the way. Something that wouldn’t allow me to write something as simple as this:

@interface MyView : UIView { // ... SingleTouchEvent m_singleTouchEvent; }

SingleTouchEvent is a custom C++ class. There’s nothing wrong with that right? There shouldn’t. But if you try and compile it, you’ll get this warning:

warning: type `SingleTouchEvent' has a user-defined constructor warning: C++ constructors and destructors will not be invoked for Objective-C fields

Some of you might be saying, no big deal, you can dynamically allocate objects and have their constructors called as usual. That’s true, but I hate allocating objects on the heap just because of something like this. My preference is always to make them member variables if I can. It’s faster, more efficient, less error prone, and easier to read. Needless to say, this was bugging the hell out of me.

I looked all over the build options in case there was some setting I could toggle to enable C++ constructors to be called, but no luck. I did a bit more research, and lo and behold, it turns out there is a custom setting you can pass directly to gcc to do exactly that! It’s nowhere in the XCode settings GUI, so you have to enter it by hand. Go to Project | Info, and in the Custom Settings section, enter the following: GCC_OBJC_CALL_CXX_CDTORS = YES

With that setting enabled, Objective-C and C++ now play together better than ever!

Without any barriers to writing new code in Objective-C, I expect it will slowly (or maybe not so slowly) replace C++ as my main language of choice for future projects.