The C++ equivalent of your example looks something like this:
// A.hpp
#include "B.hpp"
class A : public BDelegate {
public:
void classBSays ( ) { }
B* b;
};
// B.hpp
class BDelegate {
public:
virtual void classBSays( ) = 0;
};
class B {
public:
void f ( ) { delegate->classBSays( ); }
BDelegate* delegate;
};
Note that I've used inline implementation of the member functions here, for brevity's sake - you could equally implement A.classBSays()
and B.f()
in separate A.cpp
and B.cpp
files if you wanted.
In this example, the class BDelegate
is an abstract base class (ABC), equivalent to your BDelegate
protocol. By containing only pure virtual member functions (functions preceded with the keyword virtual
and with the =0
suffix), it forces its subclasses to provide implementations for those methods, much as using a @required
tag (or no tag) does in an Objective-C protocol. The fact that BDelegate
contains only such functions is what makes it an ABC.
You can emulate the Objective-C @optional
tag by specifying an empty body for the function in your ABC, which means that subclasses are not required to implement it (since it is implemented in the ABC). For example, you could emulate an optional foo
method by modifying the BDelegate
as follows:
@protocol BDelegate
- (void) classBsays;
@optional
- (void) foo;
@end
// Is approximately equivalent to:
class BDelegate {
public:
virtual void classBSays( ) = 0;
virtual void foo( ) { }
};
Using that definition, the class A
could choose whether to provide a definition for foo
or not, as is desired. Note however that this is not exactly equivalent to the Objective-C @optional
notation, because A
will still inherit BDelegate
's foo
method if it doesn't provide it's own override. With the Objective-C protocol, on the other hand, A
would have no such method at all unless it explicitly implements it itself.
A more thorough introduction to the subject is available here.