5

How much integration do C++ and Objective C have in Objective C++? I realize that Objective C++ compiles both C++ and Objective C code, but do the languages actually interact with each other?

For example can I create a template of a Objective C object? How about inheriting an Objective C class from a C++ class?

What I am basically trying to ask is do the languages mix or do they simply compile together in the same file? To what extent?

fdh
  • 5,256
  • 13
  • 58
  • 101
  • You have it kind of backwards. For an .mm file a C++ compiler compiles the Objective-C code. For an .m file a C compiler is used instead. Mixing C++ and Objective-C class hierarchies is not "normally" possible (though I'm sure there are tricks), but you can embed one class instance in the other. – Hot Licks Jan 31 '12 at 03:43

3 Answers3

2

Have a look at the Objective-C language guide section on Objective-C++ and/or the Wikipedia article.

To answer your specific questions, yes the languages can "interact". Yes, you can create a template of an Objective-C object (id is just a pointer) but don't expect to use RAII with Objective-C objects. No, you cannot derive an Objective-C class from a C++ class or a C++ class from an Objective-C class.

Barry Wark
  • 107,306
  • 24
  • 181
  • 206
2

Well it's quite common to use Objective-C++ to build applications. You can wrap Objective-C around C++ code but you can't share objects. For example you can't create an NSString object in Objective-C and trying to call the method hasSuffix: from C++ and visa versa. So to share content between those two you need to use C types like structs, chars, ints etc. It's because the Objective-C objects are only usable in the Objective-C runtime environment and the C++ objects are only usable in the C++ runtime environment. So the only thing they both share and can communicate through is C.

Maybe a little example will show you how you can interact between these two.

NSString * objcStr = [[NSString alloc] initWithString:@"Hello World!"];
std::string cppStr ([objcStr UTF8String]);
std::cout << cppStr;
dj bazzie wazzie
  • 3,472
  • 18
  • 23
1

You can call C++ Code from inside Objective-C and vise versa with some caveats. See How well is Objective-C++ supported? for more info

Community
  • 1
  • 1
Nick Haddad
  • 8,767
  • 3
  • 34
  • 38