Objective C protocols in C++

by jegeblad

One of the things I have grown to like in Obj. C is protocols. E.g.


@protocol FontSubViewDelegate
-(void) setFont:(NSString*) fontName;
-(void) openFontPanel;
-(void) changeTextSize:(double) textSize;
@end

An Obj. C class conforms to a protocol by something like this:


@interface RootViewController : UIViewController < mainviewdelegate , UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, FontSubViewDelegate, ColorToolbarDelegate, AlignmentViewDelegate, ToolbarDelegate> ...

It can get a bit messy. RootViewController conforms to 8 protocols here.

I like protocols, because it is a nice way to tie objects together in a "call-back" fashion. I've been using a similar strategy in C++ for many years now, but there it always ended up looking dirty. I would often create a functor:

struct FontSubViewCallBack {
virtual void operator()(NSString* fontName) = 0;
}

And then when I needed the functor-like class I would create a small local class which I would pass onto the function that needed the callback:

void RootViewController::doSomeFontStuff ()
{
struct LocalCallBack : public FontSubViewCallBack {
RootViewController * root;
void operator()(NSString* fontName) {
root->setFontName( fontName );
}
..
};
LocalCallBack cb(&this);
iNeedCallBack(cb);
};

Here the LocalCallBack forms a connection between my RootViewController class and the part that needs the callback. In reality we don't need the LocalCallBack. We can just let RootViewController inherit from FontSubView:

RootViewController : public WhateverClass, FontSubView {
...
void setFont(NSString* fontName);
void openFontPanel();
void changeTextSize(double textSize);
}

and implement the pure virtual functions directly in RootViewController.

There is nothing ground-breaking in this. It is just a different way to think; We take advantage of the fact that C++ classes can inherit from multiple classes and let the protocol be a pure virtual class. It doesn't even have to be pure virtual. If you have optional delegate functions you just give them an empty body.

I use many design patterns in general (e.g. singleton, factory, container, ...), but somehow I missed the delegate pattern in C++ or at least didn't know what to call it. I guess one of the advantage of learning a new friend is that you look at the ones you already know in a new light.