views:

61

answers:

1

I'm used to using Objective-C protocols in my code; they're incredible for a lot of things. However, in C++ I'm not sure how to accomplish the same thing. Here's an example:

  1. Table view, which has a function setDelegate(Protocol *delegate)
  2. Delegate of class Class, but implementing the protocol 'Protocol'
  3. Delegate of class Class2, also implementing 'Protocol'
  4. setDelegate(objOfClass) and setDelegate(objOfClass2) are both valid

In Obj-C this is simple enough, but I can't figure out how to do it in C++. Is it even possible?

+4  A: 

Basically, instead of "Protocol" think "base class with pure virtual functions", sometimes called an interface in other languages.

class Protocol
{
public:
    virtual void Foo() = 0;
};

class Class : public Protocol
{
public:
    void Foo() { }
};

class Class2 : public Protocol
{
public:
    void Foo() { }
};

class TableView
{
public:
    void setDelegate(Protocol* proto) { }
};
Terry Mahaffey
Thanks, except that I have one issue with that. The different classes, i.e. Class and Class2, are themselves subclasses already.
jfm429
@jfm429, that's why classes can have multiple ancestors.
avakar
Ah, I forgot about that. I can see a lot of problems with it, specifically with some particular class structures I've used in the past (I've studied single/multiple inheritance before and there are pros and cons, mostly cons) but in this situation it won't cause any problems.
jfm429
Okay, I thought this was good but then I had these errors: http://drp.ly/1gXq1j And yes, the "Classin" is as it appears in the error, even though it should be "Class in". Any ideas here? (EDIT: Placed the text at that link because these subcomments don't seem to be able to format with line breaks...)
jfm429
Oh, never mind. I found it. Turns out the virtual function declarations need empty function bodies. So for something like `virtual int aDelegateFunction()` I'd need to put `virtual int aDelegateFunction() { return 0; };` in the Protocol declaration. Works fine now!
jfm429
The virtual function declarations don't need empty function bodies if you declare them as pure virtual, ie with the = 0; after them like I did in the above example.
Terry Mahaffey