182

What are the main differences between Objective-C and C++ in terms of the syntax, features, paradigms, frameworks and libraries?

*Important: My goal is not to start a performance war between the two languages. I only want real hard facts. In fact, my question is not related to performance! Please give sources for anything that may seem subjective.

nicael
  • 18,550
  • 13
  • 57
  • 90
Alerty
  • 5,945
  • 7
  • 38
  • 62
  • @Oskar Kjellin: The answers of Mac and LiraNuna are both excellent answers. I cannot objectively decide which one is the best because both of them complements each others answer. – Alerty Apr 06 '10 at 22:04
  • @Alerty well I know (stumble into that rather often myself). Perhaps just mark the top one as answered which is what I do when cannot decide. I don't like when there are questions not marked as answered when they are :( – Oskar Kjellin Apr 06 '10 at 22:26
  • 2
    Put a link to the second answer in the first and vice/versa – Lee Taylor Jul 24 '12 at 14:18
  • 2
    [This guide](http://pierre.chachatelier.fr/programmation/fichiers/cpp-objc-en.pdf) gives the best comparison I've seen. – LiraNuna Mar 15 '10 at 04:18

7 Answers7

197

Short list of some of the major differences:

  • C++ allows multiple inheritance, Objective-C doesn't.
  • Unlike C++, Objective-C allows method parameters to be named and the method signature includes only the names and types of the parameters and return type (see bbum's and Chuck's comments below). In comparison, a C++ member function signature contains the function name as well as just the types of the parameters/return (without their names).
  • C++ uses bool, true and false, Objective-C uses BOOL, YES and NO.
  • C++ uses void* and nullptr, Objective-C prefers id and nil.
  • Objective-C uses "selectors" (which have type SEL) as an approximate equivalent to function pointers.
  • Objective-C uses a messaging paradigm (a la Smalltalk) where you can send "messages" to objects through methods/selectors.
  • Objective-C will happily let you send a message to nil, unlike C++ which will crash if you try to call a member function of nullptr
  • Objective-C allows for dynamic dispatch, allowing the class responding to a message to be determined at runtime, unlike C++ where the object a method is invoked upon must be known at compile time (see wilhelmtell's comment below). This is related to the previous point.
  • Objective-C allows autogeneration of accessors for member variables using "properties".
  • Objective-C allows assigning to self, and allows class initialisers (similar to constructors) to return a completely different class if desired. Contrast to C++, where if you create a new instance of a class (either implicitly on the stack, or explicitly through new) it is guaranteed to be of the type you originally specified.
  • Similarly, in Objective-C other classes may also dynamically alter a target class at runtime to intercept method calls.
  • Objective-C lacks the namespace feature of C++.
  • Objective-C lacks an equivalent to C++ references.
  • Objective-C lacks templates, preferring (for example) to instead allow weak typing in containers.
  • Objective-C doesn't allow implicit method overloading, but C++ does. That is, in C++ int foo (void) and int foo (int) define an implicit overload of the method foo, but to achieve the same in Objective-C requires the explicit overloads - (int) foo and - (int) foo:(int) intParam. This is due to Objective-C's named parameters being functionally equivalent to C++'s name mangling.
  • Objective-C will happily allow a method and a variable to share the same name, unlike C++ which will typically have fits. I imagine this is something to do with Objective-C using selectors instead of function pointers, and thus method names not actually having a "value".
  • Objective-C doesn't allow objects to be created on the stack - all objects must be allocated from the heap (either explicitly with an alloc message, or implicitly in an appropriate factory method).
  • Like C++, Objective-C has both structs and classes. However, where in C++ they are treated as almost exactly the same, in Objective-C they are treated wildly differently - you can create structs on the stack, for instance.

In my opinion, probably the biggest difference is the syntax. You can achieve essentially the same things in either language, but in my opinion the C++ syntax is simpler while some of Objective-C's features make certain tasks (such as GUI design) easier thanks to dynamic dispatch.

Probably plenty of other things too that I've missed, I'll update with any other things I think of. Other than that, can highly recommend the guide LiraNuna pointed you to. Incidentally, another site of interest might be this.

I should also point out that I'm just starting learning Objective-C myself, and as such a lot of the above may not quite be correct or complete - I apologise if that's the case, and welcome suggestions for improvement.

EDIT: updated to address the points raised in the following comments, added a few more items to the list.

Pavel
  • 1
  • 3
  • 17
  • 51
Mac
  • 14,615
  • 9
  • 62
  • 80
  • 9
    Decent list; one correction. They aren't "named parameters", but "interleaved parameters". Named and "keyword arguments" lead to confusion of thinking that some subset of the method name may be omitted. It cannot. – bbum Mar 15 '10 at 07:04
  • 7
    You forgot to enlist the most important difference: Object-C uses dynamic dispatch, whereas C++ uses static dispatch. In other words, code compiled by an Objective-C compiler will have the class responsible for responding to a message determined at runtime; code compiled by a C++ compiler have this information calculated and compiled-in at compiletime. – wilhelmtell Mar 15 '10 at 19:15
  • @bbum, wilhelmtell: Excellent points both - I've updated my answer to reflect your comments. – Mac Mar 15 '10 at 22:28
  • 2
    Just a slight correction to the second point: A method's name in Objective-C is called its *selector* — the method *signature* refers to the types the method takes and returns (see, for example, the NSMethodSignature class). – Chuck Mar 15 '10 at 22:39
  • 9
    @wilhelmtell: The C++ compiler knows only the superclass at compile time. At run time the actual class could be any descendant. This is also a form of dynamic dispatch, but not the same form as is used in Objective C. Just be careful with those technical terms! – Norman Ramsey Mar 16 '10 at 01:15
  • 5
    +1 Good list. However, Objective-C also uses `void*` and `NULL`, just not for objects. You can use any C-style pointer in Obj-C, and many API calls actually pass or return values by reference, in which case `NULL` is frequently used. – Quinn Taylor Mar 16 '10 at 02:49
  • 3
    @wilhelmtell - I dunno anything about objective-C, but in C++ you CAN dynamically have a different class respond to a function call, but you'd need to have something like an array of pointers to a base class, and then the ACTUAL classes that are "hanging" off of it. While all classes there need to be sub-classes, a method call WILL call different methods depending on the class, at run-time. – Kevin Anderson Mar 16 '10 at 22:36
  • 1
    In Objective-C, you can create a class at runtime. There are also no namespaces in Objective-C. – dreamlax Mar 16 '10 at 22:40
  • 3
    1) C++ can have named parameters too. See http://cpp-netlib.github.com/0.9.1/reference_http_server.html#constructor for an example. 2) Generally, calling a method on a null pointer in c++ won’t necessarily segfault. Most implementations segfaults when you access a member variable. – Paul Fultz II Feb 22 '12 at 16:49
  • 1
    @Paul: thanks for your comments. First, please note that my original terminology was incorrect (as pointed out in comments above), and the link you posted talks about a mechanism that *simulates* named parameters (but is not exactly the same thing). Second, almost every non-static member function in C++ will access a member variable (even if it is just the implicit `this`), so if you manage to call a member function without it segfaulting, you're just lucky. In Objective-C on the other hand, dynamic dispatch *ensures* that messaging `nil` is ok and will *not* cause a segfault. – Mac Feb 22 '12 at 21:13
  • 1
    I would add that SEL is not a function pointer but rather a reference to its name. IMP is the actual function pointer. – Cthutu May 16 '13 at 20:57
  • you can also use TRUE and FALSE in ObjC – eulr Oct 27 '13 at 14:36
  • 1
    +1 for the exhaustive list. How about 1. in obj-C everything has to be inherited (at least from NSObject), while in C++ we have base classes, 2. C++ allows for default argument values while Obj-C doesn't 3. There are delegates in Obj-C, I don't a C++ equivalent... perhaps multiple inheritance. ... or did I simply miss somethings? – Nikhil J Joshi Nov 16 '13 at 12:41
  • I think most importantly, obj-c is dynamically typed, while C++ is static – kevin Mar 21 '14 at 22:51
  • 1
    many "Objective-C lacks…" should be "Objective-C doesn't need…" – vikingosegundo Apr 08 '14 at 18:37
  • 3
    @NikhilJJoshi: Obj-C need not inherit everything from NSObject (E.g. NSProxy).You can have your own root classes. Also delegation is a design pattern which can be implemented in C++ too. See http://stackoverflow.com/questions/9568150/what-is-a-c-delegate – Rakesh Jan 12 '15 at 17:42
  • 2
    After C++11, it is possible (and usually recommended) to use `nullptr` instead of `NULL`. As far as I understand `NULL` is just a macro for 0, while `nullptr` will do some type checking to check that you're assigning to a pointer. – bobbaluba Jun 08 '15 at 14:35
36

While they are both rooted in C, they are two completely different languages.

A major difference is that Objective-C is focused on runtime-decisions for dispatching and heavily depends on its runtime library to handle inheritance and polymorphism, while in C++ the focus usually lies on static, compile time, decisions.

Regarding libraries, you can use plain C libraries in both languages - but their native libraries are completely different.

Of interest though is that you can mix both languages (with some limitations). The result is called Objective-C++.

RyanZim
  • 6,609
  • 1
  • 27
  • 43
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
  • updated link: [Objective-C++](https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectiveC.html) – IcyIcicle Jun 30 '20 at 05:19
7

Off the top of my head:

  1. Styles - Obj-C is dynamic, C++ is typically static
  2. Although they are both OOP, I'm certain the solutions would be different.
  3. Different object model (C++ is restricted by its compile-time type system).

To me, the biggest difference is the model system. Obj-C lets you do messaging and introspection, but C++ has the ever-so-powerful templates.

Each have their strengths.

Rev316
  • 1,920
  • 2
  • 19
  • 24
6

They're completely different. Objective C has more in common with Smalltalk than with C++ (well, except for the syntax, really).

Dean Harding
  • 71,468
  • 13
  • 145
  • 180
5

As others have said, Objective-C is much more dynamic in terms of how it thinks of objects vs. C++'s fairly static realm.

Objective-C, being in the Smalltalk lineage of object-oriented languages, has a concept of objects that is very similar to that of Java, Python, and other "standard", non-C++ object-oriented languages. Lots of dynamic dispatch, no operator overloading, send messages around.

C++ is its own weird animal; it mostly skipped the Smalltalk portion of the family tree. In some ways, it has a good module system with support for inheritance that happens to be able to be used for object-oriented programming. Things are much more static (overridable methods are not the default, for example).

Michael Ekstrand
  • 28,379
  • 9
  • 61
  • 93
4

Objective-C is a more perfect superset of C. In C and Objective-C implicit casting from void* to a struct pointer is allowed.

Foo* bar = malloc(sizeof(Foo));

C++ will not compile unless the void pointer is explicitly cast:

Foo* bar = (Foo*)malloc(sizeof(Foo));

The relevance of this to every day programming is zero, just a fun trivia fact.

Igor Zevaka
  • 74,528
  • 26
  • 112
  • 128
  • 1
    Second example is not C++ code. It's C code that gave you an error when you tried to compile it with C++ compiler. If you want old C++ as close to original, you'd write `Foo* bar = reinterpret_cast< Foo* >(malloc(sizeof(Foo));` then maybe use inplace constructor.. But as of today its Modern C++ is more like `auto bar = new Foo(constructorArg);` actually you dont need malloc, and either callic, you may use `std::vector::reserve`, and `std::vector::emplace_mack` – xakepp35 Mar 05 '20 at 20:53
2

Obj-C has much more dynamic capabilities in the language itself, whereas C++ is more focused on compile-time capabilities with some dynamic capabilities.

In, C++ parametric polymorphism is checked at compile-time, whereas in Obj-C, parametric polymorphism is achieved through dynamic dispatch and is not checked at compile-time.

Obj-C is very dynamic in nature. You can add methods to a class during run-time. Also, it has introspection at run-time to look at classes. In C++, the definition of class can't change, and all introspection must be done at compile-time. Although, the dynamic nature of Obj-C could be achieved in C++ using a map of functions(or something like that), it is still more verbose than in Obj-C.

In C++, there is a lot more checks that can be done at compile time. For example, using a variant type(like a union) the compiler can enforce that all cases are written or handled. So you don't forget about handling the edge cases of a problem. However, all these checks come at a price when compiling. Obj-C is much faster at compiling than C++.

Paul Fultz II
  • 17,682
  • 13
  • 62
  • 59
  • 3
    If you're going to talk about prices, be fair! Conversely, Obj-C is much slower at resolving dynamic method calls at runtime than C++. And I'd argue that compilation speed is a relative triviality compared to runtime speed. I'm sure Obj-C offers many benefits due to its more dynamic dispatch, but there's a trade-off there. – underscore_d Jul 31 '16 at 17:04
  • 1
    True, there is a tradeoff between runtime vs compile time cost. However, compile time is not always trivial. Using heavy metaprogramming and EDSLs libraries in C++(such as Boost.Spirit) can have a drastic effect on compile time, while producing very fast code at runtime. – Paul Fultz II Aug 01 '16 at 11:15
  • 1
    Sure, I was oversimplifying relative to the POV of simpler codebases... With very complex codebases, recompiling to test small changes might make development very tedious, which isn't a triviality. But is this something we can really compare between the two? Can such libraries, so dependent on C++ compile-time features, be somehow reimagined in Objective-C & shown to compile faster? i.e. Does the statement "Obj-C is much faster at compiling than C++" refer to equivalent codebases for which a replicable speedup can be measured? Otherwise we're comparing the time taken to grow apples vs oranges. – underscore_d Aug 01 '16 at 11:26