Search code examples
iphoneobjective-cobjective-c++

Objective C and Objective C++


C files can be modified from .c to .m files and can be called from other Objective C files (.m files).

C++ files can be modified from .cpp to .mm files and can be called from other Objective C++ files (.mm files).

.m files can be called from .mm files. But .mm files cannot be called from .m files.

Is Objective C++ coding necessary in iPhone development as UI will be in Objective C and any other protocols implemented can't be Objective C++ as this (protocols written) will be called from the UI which is written Objective C.

In what scenario is this Objective C++ coding used?


Solution

  • .m files can be called from .mm files. But .mm files cannot be called from .m files.

    Not sure what you mean by this, but I think it's wrong.

    The "Objective" part of Objective-C(++) is the same in both languages. It doesn't matter whether the implementation is Objective-C or Objective-C++, the objects will be fully interoperable.

    What does matter is the header file in which the interface is declared. For instance:

    @interface Foo
    {
       CPPFoo myFoo; // A C++ object
    }
    
    @end
    

    can't be included in a normal Objective-C .m file because C++ classes are illegal in C. One way to get around this is to use forward declarations and pointers e.g.

    #if defined __cplusplus
    class CPPFoo;
    #else
    typedef struct CPPFoo CPPFoo;
    #endif
    
    @interface Foo
    {
       CPPFoo *myFoo; // NOTE: a pointer to a C++ object
    }
    
    @end
    

    You need to new the pointer in -init and delete it in -dealloc/-finalize


    Is Objective C++ coding necessary in iPhone development

    No. I used to think (coming from a C++ background) that it would be best to use C++ everywhere and Objective-C only in the UI. However, it didn't take long for me to realise that Objective-C's object model is better than that of C++. So now I would consider C++ in only two cases:

    • when interfacing to libraries that were written in C++
    • if performance is important and you need an built in Object model (i.e. you don't want to use pure C)