TweetFollow Us on Twitter

C and Objective C Compared

Volume Number: 13 (1997)
Issue Number: 3
Column Tag: Rhapsody

C++ Versus Objective-C

By Michael Rutman, independent consultant

What will programming in Objective-C mean to the C++ programmer

Different Object Oriented Languages

Almost all of us have heard the term object oriented programming, and most of us have used C++. How will Apple's purchase of NeXT, and NeXT's framework using Objective-C affect us as we develop software? If we know C++ already, how hard will it be to get up to speed on Objective-C? Many people will agree that once they understand the concepts of object oriented programming it doesn't matter which language they use. To a degree this is true, but development is easier if the programmer adopts a programming philosophy based on the peculiarities of the language.

C++ has a very diverse syntax, many language extensions, and hundreds of quirks. In my first year of C++ programming, I thought that I understood all the important concepts. In my second year, I thought I had it mastered. However, after all this time, I'm still learning about esoteric things that can be done in C++, and the bizarre syntax needed to access those features.

On the other hand, Objective-C is a blend of C and Smalltalk. Most of it is straight C, with embedded Smalltalk. Assuming you already know C and C++, then you know most of the syntax of Objective-C. When reading Objective-C code, an easy way to understand the syntax is to know that [anObject aMethod] in Objective-C is the same as anObject->aMethod() in C++. This is over-simplification, but it is a useful rule for getting started.

How Do I Declare an Objective-C Object?

C code is the same in Objective-C and C. Unlike C++, where a few K&R C constructs have been changed, straight C in Objective-C is straight out of K&R. Many people remember how easy it is to write sloppy code in K&R C. Fortunately, NeXT uses gcc, which has adopted ANSI C. This means that we can write sloppy code for NeXTSTEP, but activating the ANSI C violation warnings can help us clean it up.

Classes are different between C++ and Objective C, especially in the declaration of the classes. In C++, each class is a structure, and variables and/or methods are in that structure. In Objective-C, variables are in one section of the class, and methods in another. In C++, methods look like C functions, in Objective-C, methods look like Smalltalk methods. Listing 1 shows two examples of class declarations. The first class is a C++ class, the second is the same class in Objective-C. NeXTSTEP allows programmers to merge C++ and Objective-C in the same file.

Listing 1

class Foo : public Bar
 Foo(int aValue);
 int  CallFoo(intaValue);
 int  Value();
 static (foo *)MakeFoo(int aValue);
 int  myVariable;
 int  value;

 int  myVariable;
 int  value;

+(Foo *)MakeFoo:(int)aValue;
- free;
- (int)callFoo:(int)aValue;
- (int)value;

Some things to note

The Objective-C class allows a method and a variable with the exact same name. In C++, they must be different. In Listing 1, the method and variable use different cases to differentiate them.

Objective-C does not respect public and private as does C++. It knows about them, but doesn't really use them.

Objective-C does not have a constructor or destructor. Instead it has init and free methods, which must be called explicitly. There is nothing in the Objective-C language that requires them to be called init and free, it's just a standard practice.

Objective-C uses + and - to differentiate between factory and instance methods, C++ uses static to specify a factory method.

How Does an Objective-C Method Look?

The declaration of a method is more like Smalltalk than C, but once in a method, it is easy to follow. Each method call is put inside of square brackets ([]). Listing 2 shows a C++ and an Objective-C method.

Listing 2:

intfoo::callFoo(int foo)
 int    count;
 int    result = 0;
 HelperObject  object;

 for  (count = 0; count < foo; count++)
 result += object.Value(count); 
 return result;

 int    count;
 int    result = 0;
 HelperObject  *anObject = [[HelperObject alloc] init];

 for  (count = 0; count < foo; count++)
 result += [anObject value:count];
 [anObject free];
 return result;

These two languages, despite doing the same thing, look quite a bit different. The declaration is also different. In C++, we use a C declaration, but add the class name with some colons. In Objective-C, we use a Smalltalk definition. The type is declared, and the function name is followed by : and parameters. Each parameter is separated by colons. In addition, each parameter can be named, though the parameter name is only used for overloading. So, we can have two methods in the same object:

- (int)foo:(int)x bar:(int)y;
- (char *)foo:(int)x baz:(int)y;

The two methods in these functions, even though having the same name, have different return types. In C++ this is not permitted, but in Objective-C it's perfectly valid. In reality, their names are foo:bar: and foo:baz:, and there is no function overloading, but it is as close to function overloading as Objective-C gets.

Once in a method, Objective-C is read like straight C with embedded Smalltalk. Note that the HelperObject has to be created and destroyed manually, and also note that the HelperObject cannot be on the stack.

The last thing to note is the syntax of a method call. object->method(parameter) becomes [object method:parameter].

On occasion, Objective-C code will have a method with no type declared for its return value, or for some of its parameters. In C, when there isn't a type, then it is an int. In Objective-C, though, it is an id, which is a generic object type. Unlike C++, where there is strong typing, Objective-C allows weak typing for generic objects.

What Does Objective-C Have that C++ is Missing?

Objective-C offers runtime binding. C++ tries to fake it with mix-in classes and virtual functions, but after using runtime binding, I find that C++ is a frustrating language. For example, in most C++ frameworks, Windows are a subclass of a View object because that's the only way for both of them to have display methods that can be called by any object. In Objective-C, there can be display methods in any object, and at runtime the correct method will be called. This means that Window class and View class don't need a common superclass to define Display. No need to bastardize the object chain to get around the lack of runtime binding. On the other hand, Objective-C can have runtime errors, where C++ will catch those errors at compile time.

Another advantage of runtime binding is avoiding the "fragile base class" problem found in C++. This is when there is a change in a class in a shared library, the lookup tables will change, and this will break every app using the library. Objective-C doesn't have this problem because each method is looked up at runtime.

A third advantage of runtime binding is dynamic linking. Apple is constantly coming out with new shared library formats, such as CFM, ASLM, and SOM. Since there is runtime binding in Objective-C, loading a shared library is straight forward. They come in bundles, which are just object files, they get loaded with one call, and their objects are added to the runtime environment. Their format is defined by the language.

Yet another advantage of Objective-C is seen in Interface Builder. Metrowerks Constructor is an amazing attempt to get an interface builder working in C++, but it pales to what NeXT provided 10 years ago with Interface Builder. Interface Builder allows the user to create User Interface, as does Constructor, but with a twist, Interface Builder is integrated into the development environment. In Constructor, each class has to have a 4 letter signature that links the class in Constructor and the class in the code. The code also has to register the classes with the same 4 letter signature and a construction method that creates an instance of that custom class. When a class is created in Interface Builder it has to have only a name. Interface Builder will even create stubbed out files for the project. Objective-C uses the class names to match up classes in Interface Builder to classes in the code. No 4-letter codes; no registration routines.

Two of the best features of Objective-C, proxies and categories, also come from the runtime binding. Occasionally, there is a root object that is missing some important functionality. We really want to add that functionality, but the only way in C++ of doing that is to modify the class library. Objective-C provides two means of adding functionality to a library without recompiling. The first is called proxy. As long as there aren't any extra instance variables, any subclass can proxy itself as its superclass with a single call. Each class that inherits from the superclass, no matter where it comes from, will now inherit from the proxied subclass. Calling a method in the superclass will actually call the method in the subclass. For libraries where many objects inherit from a base class, proxying the superclass can be all that is needed.

Categories are like proxies, but instead of replacing the superclass they just extend the superclass. In C++, each object must be explicitly declared, and each subclass must know everything about the superclass at compile time. In Objective-C, new functionality can be added to existing classes by adding a new category. Shared libraries that depend on a base class that has been extended will continue to work, and new classes created can call the additional methods.

What Does C++ Have that Objective-C is Missing?

C++ has tons of features not found in Objective-C. Objective-C is a simpler language. Objective-C tries to blend the purity of Smalltalk with the simplicity of C. However, some people have said that Objective-C blends the lack of readability of C with the limitations of Smalltalk.

The biggest C++ feature that Objective-C does not have is constructors/destructors. In Objective-C, the initialization and free methods have to be called manually. With Foundation Kit, NeXTSTEP provides garbage collection, so objects don't have to be explicitly freed, but the destructors won't be called when an object falls out of scope. One C++ object I love is a HandleLock. A HandleLock is used to lock a handle, when it falls out of scope, the handle's state is restored. No need to remember to unlock the handle. This capability isn't available in Objective-C.

Objective-C also does not allow stack based objects. Each object must be a pointer to a block of memory. Memory allocations on the Macintosh are expensive. Under NeXTSTEP, virtual memory and a decent memory manager means little heap fragmentation, and therefore, memory allocations are much cheaper, so embedded objects are not as important. However, putting an object on the stack or inside another class without additional memory allocations is a nice feature that I miss when I program in Objective-C.

Another missing feature is overloading. Objective-C has a work-around for method overloading, but none for operator overloading. Personally, I don't like operator overloading, so I don't really miss it. Listing 3 shows a C++ and Objective-C objects using method overloading.

Listing 3:

class foo
 int  foo(char *fooValue, int number);
 int  foo(char *fooValue, char *string);

(char *)fooValue byInt:(int)number;
- (int)fooByString:(char *)fooValuebyString:string;

In Objective-C the message overloading is faked by naming the parameters. C++ actually does the same thing but the compiler does the name mangling for us. In Objective-C, we have to mangle the names manually.

One of C++'s advantages and disadvantages is automatic type coercion. At times, it is nice to be able to pass an object of one type and have it automatically converted to the correct type. Unfortunately, often enough, it is doing the wrong kind of coercion, and a nasty bug appears. In Objective-C, to coerce a type, it must be explicitly cast.

Another feature C++ has that is missing in Objective-C is references. Because pointers can be used wherever a reference is used, there isn't much need for references in general. Some programmers like them for stylistic reasons though, and they will likely miss them.

Templates are another feature that C++ has that Objective-C doesn't. Templates are needed because C++ has strong typing and static binding that prevent generic classes, such as List and Array. With templates, a List of Int class easily can be created. Under Objective-C, List classes hold objects, and the List class does not care what kind of object it is holding. C++ will guarantee that each object put in the List of Int is an int, at least theoretically guarantee it, while Objective-C makes no such guarantee. Objective-C's runtime binding makes List easier to use, but the safety of compile-time binding is lost.

Both Objective-C and C++ offer abstract objects, but Objective-C allows it only by generating runtime errors when instantiated. C++ compilers will not allow an instantiation of an abstract object. This is another example of C++ doing static binding and Objective-C doing runtime binding.

Philosophy of Each Language

Think of Objective-C objects like a factory, and C++ objects like a home business. Objective-C objects tend to be large, self contained, and do everything imaginable. C++ objects tend to be small and to the point. C++ objects also tend to come in groups, where Objective-C objects tend to be more standalone. This does not mean that there can't be small Objective-C objects and large C++ objects, it only means that the trend is for Objective-C objects to be large, standalone objects and C++ objects to be small and dependent on one another.

When programming in C++, each and every concept, no matter how small, should get its own class. Applications typically have hundreds, if not thousands of classes, each one small, and all interconnected. This can lead to name collisions, but C++ has solved some of these problems by using NameSpaces. Even without NameSpaces, C++ can avoid name collisions by including only needed header files. Two classes can have the same name if they are private and never included by the same file.

Objective-C objects should be able to stand on their own. There are no private objects, only one name space, and object names are resolved at runtime. Having thousands of Objective-C objects is asking for trouble.

C++, with its zero overhead for non-virtual classes, encourages programmers to subclass ints, rects, and any other data structure. Writing a little bit of code can give range checking, type checking, value checking, or any other kind of checking imaginable. Objective-C has a lot of overhead for an object, and there is no operator overloading. It is not practical to have Objective-C classes for rects, ints, or other small data structures.

Despite many applications having been written in C++, and C++ having many features over Objective-C, I find writing applications in Objective-C much easier and faster than writing the same applications in C++. One of the biggest reasons for this is the number of objects found in an application. In Objective-C, having less than 100 objects in an application lets me keep the entire structure of the program in my head. In C++, where each concept is its own object, I am constantly looking for which object contains the functionality I'm looking for.

Another reason why Objective-C is faster to develop in is that it is a simpler language. I have seen programmers spend days trying to get the syntax of an esoteric C++ function just right. Objective-C does not have as many areas where language lawyers thrive. The worst part of C++'s esoteric syntax is other programmers might not be able to understand some of the more complex C++ code.

The biggest reason for the faster developement time is the self-contained object. Objective-C objects tend to be self-contained, so if you need functionality, you only need to include that one object, or occasionally a small number of related objects. C++ objects, on the other hand, tend to come in groups. Each time you want to include functionality from an object, you are likely required to include an additional 10-20 objects.

Which Language Should I Use if
I am Programming NeXTSTEP?

The wonderful part about NeXTSTEP is that it supports both C++ and Objective-C. However, it's framework is in Objective-C, and calls to the framework are best left in Objective-C. While working with the framework, you are best off programming in Objective-C.

However, if you want a lightweight object with constructors and destructors, you can throw in a C++ object anywhere you want. With C++ objects, you can have the best of both worlds. Listing 4 shows an example of using both languages at the same time.

Listing 4:

class ListLocker
 List *aList;
 ListLocker(List *aList)  {theList = aList; [theList lock];}
 ~ListLocker()   {[theList unlock];}

- (void)objectiveCMethod:(List *)myList
 ListLocker lock(myList);
 [myList doSomething];

In Listing 4 we create a lightweight C++ object that will lock and unlock an Objective-C class as needed. In our Objective-C method, we put the C++ object on the stack, which locks the list, and when it falls out of scope the destructor will unlock the stack.

So, my advice is to use both as you need them. Use the flexibility of Objective-C for most of your work, and use the lightweight C++ objects as tools to help you.

If you want to get started exploring Objective-C, check out Tenon's CodeBuilder at <>. More information about Objective-C can be found on NeXT's site at <>.

Apple Inc.
Microsoft Corpora
Google Inc.

MacTech Search:
Community Search:

Software Updates via MacUpdate

Starcraft II: Wings of Liberty
Download the patch by launching the Starcraft II game and downloading it through the connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
MYStuff Pro 2.0.16 - Create inventories...
MYStuff Pro is the most flexible way to create detail-rich inventories for your home or small business. Add items to MYStuff by dragging and dropping existing information, uploading new images, or... Read more
TurboTax 2013.r17.002 - Manage your 2013...
TurboTax guides you through your tax return step by step, does all the calculations, and checks your return for errors and overlooked deductions. It lets you file your return electronically to get... Read more
TrailRunner 3.8.769 - Route planning for...
Note: While the software is classified as freeware, it is actually donationware. Please consider making a donation to help support development. TrailRunner is the perfect companion for runners,... Read more
Flavours 1.1.10 - Create and apply theme...
Flavours is a Mac application that allow users to create, apply and share beautifully designed themes. Classy Give your Mac a gorgeous new look by applying delicious themes! Easy Unleash your... Read more
Spotify - Stream music, creat...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue... Read more
SlingPlayer Plugin - Browser...
SlingPlayer is the screen interface software that works hand-in-hand with the hardware inside the Slingbox to make your TV viewing experience just like that at home. It features an array of... Read more
S.M.A.R.T. for USB and FireWire Drives 0...
S.M.A.R.T. for USB and FireWire Drives is a kernel driver for OS X external usb or firewire drives. It extends the standard driver behaviour by providing access to drive smart data. The interface to... Read more

Latest Forum Discussions

See All

148Apps Live on Twitch: Pivvot’s Looper...
On our latest Twitch stream, we’ll be playing a pair of minimalist arcade games, one that just got a big content update in Pivvot, and another that was inspired by it in 15 Coins. Whitaker Trebella, creator of Pivvot, will discuss the new modes... | Read more »
Word Cubes Review
Word Cubes Review By Jordan Minor on April 15th, 2014 Our Rating: :: SQUARESVILLEUniversal App - Designed for iPhone and iPad Word Cubes is fine, but it is barely any different from any other word game.   | Read more »
PAX East 2014 – Desert Fox: The Battle o...
PAX East 2014 – Desert Fox: The Battle of El Alamein is Coming to iOS Soon Posted by Rob Rich on April 15th, 2014 [ permalink ] Shenandoah Studio has become one of the go-to developers for war games on iOS, with | Read more »
Tank of Tanks Review
Tank of Tanks Review By Carter Dotson on April 15th, 2014 Our Rating: :: TANKS A LOT!iPad Only App - Designed for the iPad This multiplayer game played on a single iPad is simple, chaotic fun.   | Read more »
PAX East 2014 – Dungeon of the Endless J...
PAX East 2014 – Dungeon of the Endless Just Might Have a Shot at an iPad Release Posted by Rob Rich on April 15th, 2014 [ permalink ] I think it’s fair to say that | Read more »
SideSwype Review
SideSwype Review By Carter Dotson on April 15th, 2014 Our Rating: :: ON YOUR SIDEUniversal App - Designed for iPhone and iPad SideSwype is a puzzler that takes inspiration from Threes, but becomes its own incredibly fun game.   | Read more »
PAX East 2014 – Bigfoot Hunter Invites P...
PAX East 2014 – Bigfoot Hunter Invites Players on a Wild and Wooly Photo Safari Posted by Rob Rich on April 15th, 2014 [ permalink ] Yeti. Sasquatch. Wendigo. | Read more »
Dungeon Quest Review
Dungeon Quest Review By Cata Modorcea on April 15th, 2014 Our Rating: :: NO STORY, BUT GOOD FUNUniversal App - Designed for iPhone and iPad Dungeon Quest does a lot of things right, but ultimately forgets about one of the core... | Read more »
Tempo AI and Speek Join Forces to “Kill...
Tempo AI and Speek Join Forces to “Kill the Conference Call PIN” Posted by Rob Rich on April 15th, 2014 [ permalink ] Today Tempo AI, makers of Tempo Smart Calendar, and | Read more »
Fighting Fantasy: Starship Traveller Rev...
Fighting Fantasy: Starship Traveller Review By Jennifer Allen on April 15th, 2014 Our Rating: :: A SIGNIFICANT VOYAGEUniversal App - Designed for iPhone and iPad Continuing the release of Fighting Fantasy titles, Starship Traveller... | Read more »

Price Scanner via

Save $50 on Mac mini Server
B&H Photo has the 2012 Mac mini Server on sale for $949 including free shipping plus NY sales tax only. Their price is $50 off MSRP. Read more
PhatWare’s “Ultimate Writing App For iOS” Ren...
PhatWare Corp. has announced it has renamed its new WritePro word processing app for iPhone and iPad: WritePad Pro. The decision to change the app’s name to leverages the strong brand awareness and... Read more
Full Resolution Photo Editor Tint Mint 1.0 Re...
California based independent developer, Jeffrey Sun, creator of the iOS app Modern Editor, has released Tint Mint, a new photography app for editing enthusiasts. The app costs a dollar, and it packs... Read more
16GB iPad mini (Apple refurbished) available...
The Apple Store has refurbished 1st generation 16GB iPad minis available for $249 including free shipping. Both black and white models are available. Read more
Save $120 on the 27-inch 3.2GHz Haswell iMac
B&H Photo has the 27″ 3.2GHz iMac on sale for $1679.99 including free shipping plus NY sales tax only. Their price is about $120 off MSRP. Read more
Using a Mac Doesn’t Eliminate The Heartbleed...
Low End Mac’s Dan Knight notes that any time you visit a website with an https: prefix or see that secure lock icon on your browser, some type of security software is busy trying to protect your data... Read more
AirPrint Basics Tutorial Posted
A new Apple Knowledge Base article helps get you started using AirPrint, the Apple protocol that enables instant printing from iPad, iPhone, iPod touch, and Mac without the need to install drivers or... Read more
Speed Tips For Running LibreOffice On The Mac
LibreOffice is my favorite of several free, open-source application suites, and the one I have configured on my Mac as my default app for Word documents that one frequently has to deal with. It also... Read more
Snag a 15-inch Retina MacBook Pro for $115 of...
B&H Photo has 2013 15″ Retina MacBook Pros on sale for up to $115 off MSRP for a limited time. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.3GHz Retina MacBook Pro: $2489.99... Read more
MacBook Airs on sale for $50 to $100 off MSRP
Several resellers are offering $50-$100 discounts on 11″ and 13″ MacBook Airs today, including Amazon, Best Buy, B&H, and others. See the breakdown of deals on our MacBook Air Price Tracker,... Read more

Jobs Board

Position Opening at *Apple* - Apple (United...
**Job Summary** Every day, business customers come to the Apple Store to discover what powerful, easy-to-use Apple products can do for them. As a Business Leader, Read more
Position Opening at *Apple* - Apple (United...
…challenges of developing individuals, building teams, and affecting growth across Apple Stores. You demonstrate successful leadership ability - focusing on excellence Read more
Position Opening at *Apple* - Apple (United...
…Summary** As a Specialist, you help create the energy and excitement around Apple products, providing the right solutions and getting products into customers' hands. You Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** The Apple Store is a retail environment like no other - uniquely focused on delivering amazing customer experiences. As an Expert, you introduce people Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** Being a Business Manager at an Apple Store means you're the catalyst for businesses to discover and leverage the power, ease, and flexibility of Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.