C++ question: feature similar to Obj-C protocols?
Asked Answered
C

1

16

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?

Caviar answered 28/6, 2010 at 6:58 Comment(0)
J
26

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) { }
};
Julius answered 28/6, 2010 at 7:2 Comment(7)
Thanks, except that I have one issue with that. The different classes, i.e. Class and Class2, are themselves subclasses already.Caviar
@jfm429, that's why classes can have multiple ancestors.Buckling
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.Caviar
Okay, I thought this was good but then I had these errors: 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...)Caviar
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!Caviar
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.Julius
I have another question: Let’s say Vehicle is a base class as you showed us... I only declared in a header file since this is only the protocol or the interface or the... base class in this case? Or does it require an implementation (Cpp ) file ? ... also: If I need to make a subclass of Vehicle and make a car that has additional properties and methods... And then if I have another class that expects a Vehicle in a method or function, is it ok to declare it that way and pass it a Car subclassed instance, knowing that it fulfills all the vehicles requirements?Heartache

© 2022 - 2024 — McMap. All rights reserved.