Objective-C++ is the union of the Objective-C and C++ syntax sets.
Objective-C++ is the union of the Objective-C and C++ syntax sets. Objective-C is, by definition, a strict superset of the C language; C++ is similarly regarded as such in practice (albeit without qualifying as a strict superset, q.v. this illustrated answer) and the conceptual union of these two supersets is the basis for the Objective-C++ language.
The practical use of Objective-C++ is contingent on the compiler in question. Briefly, compiling in Objective-C++ mode puts all of the basic C-family compiler settings in play, plus all C++ extensions, plus all Objective-C extensions, plus its own niche concerns (e.g. its ABI corner-case behavior). Despite this preponderance of abusable options, it is pretty straightforward to compile Objective-C++, as part of a larger project (as with parts of OpenFrameworks) or as the basis for a project in its own right (i.e. Pivotal Labs’ Cedar).
For the most part, two languages can be fairly freely intermixed – one important caveat being a class definition in C++ cannot inherit from an Objective-C class; likewise, Objective-C classes can’t inherit from C++ classes.
One can define Objective-C classes with:
pointer ivars for pointers to dynamically allocated instances of C++ types
value ivars for inline storage of C++ data, for default-constructable types
class and instance methods that receive and/or return C++ types
- pass by value, by pointer, by reference (lvalue or rvalue‡)
std::atomic
values accessible concurrently from bothNSThread
and GCD alongsidestd::thread
primitives‡
One can define C++ classes:
- containing pointer-to-Objective-C-class members (e.g.
NSURL*
,NSString*
,NSImage*
etc)- With caveats on object lifecycle management qua ARC and GC
- as templates accepting
NSObject
subclasses astypename
parameters - with method members that accept and/or return
NSObject
subclass instances- By pointer as per
[OCType alloc]
message return value
- By pointer as per
- with method template members that accept
NSObject
subclasses astypename
parameters - that use block pointers as expected (e.g. in
typedef
andusing
‡ declarations)
Notably, Objective-C++ does not allow for:
- Templated Objective-C class structures of any kind –
template <…>
declaration syntax is incompatible with the@implementation
/@interface
definition-marker grammar rules - Templated Objective-C class or instance methods – e.g. the following code is tempting to try, but totally invalid:
@implementation NSSomeThing : NSObject
template <typename T>
+ (T) getValue {
return static_cast<T>(value);
}
@end
… C++ templates and Objective-C classes use separate, incompatible preprocessing paths in their respective compilation processes.
‡ may be used with C++11 compiler support