Im pretty familiar with obj-c and now I´m trying to dig deeper in C++.
Im looking for a C++ equivalent for obj-c´s delegation pattern.
Im pretty familiar with obj-c and now I´m trying to dig deeper in C++.
Im looking for a C++ equivalent for obj-c´s delegation pattern.
There isn't really a 1:1 equivalent. Objective C is a somewhat dynamically typed language. A
protocol
in Obj-C is like a promise that functions ('selectors') with certain signatures are going to exist at run-time. You don't have to implement them if you don't want to, but you should if you don't want things to crash at runtime, unless they're marked@optional
.C++ by comparison is 100% statically typed. If you say some function should exist, then it has to exist, or the program will not compile. If a superclass declares a function as abstract then subclasses must inherit it. Multiple inheritance (which you need if you want a class to implement multiple decoupled protocols) is a minefield.
The advantage of static typing (C++) is that you can know at compile time whether your program is functionally complete (whether there's code for every place there should be code). However, the cost of this is that sometimes you have to come up with other solutions to fill in for Obj-C's protocols and delegation.
The term "delegate" could still well apply. There isn't a syntactic pattern but you model it with a framework using the usual tools.
There's a lot of code here, but the interface is quite clean. What the user must do is just a little code at the bottom. There's still some boilerplate related to constructors, but this will go away in the future with the C++11 "inheriting constructors" syntax.
See it run: https://ideone.com/IRp5rJ
Instead of conforming to a protocol, you just inherit the class (protocol). A small example: