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
{
public:
 Foo(int aValue);
 ~Foo();
 int  CallFoo(intaValue);
 int  Value();
 static (foo *)MakeFoo(int aValue);
private:
 int  myVariable;
 int  value;
}

Bar
{
 int  myVariable;
 int  value;
}

+(Foo *)MakeFoo:(int)aValue;
-initFoo:(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;
}

intcallFoo:(int)foo
{
 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
{
public:
 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
{
private:
 List *aList;
public:
 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 <http://www.tenon.com/products/codebuilder/>. More information about Objective-C can be found on NeXT's site at <http://www.next.com/NeXTanswers/htmlfiles/138htmld/138.html/>.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

LaunchBar 6.18.5 - Powerful file/URL/ema...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Affinity Designer 2.3.0 - Vector graphic...
Affinity Designer is an incredibly accurate vector illustrator that feels fast and at home in the hands of creative professionals. It intuitively combines rock solid and crisp vector art with... Read more
Affinity Photo 2.3.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
WhatsApp 23.24.78 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Adobe Photoshop 25.2 - Professional imag...
You can download Adobe Photoshop as a part of Creative Cloud for only $54.99/month Adobe Photoshop is a recognized classic of photo-enhancing software. It offers a broad spectrum of tools that can... Read more
PDFKey Pro 4.5.1 - Edit and print passwo...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Skype 8.109.0.209 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
OnyX 4.5.3 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
CrossOver 23.7.0 - Run Windows apps on y...
CrossOver can get your Windows productivity applications and PC games up and running on your Mac quickly and easily. CrossOver runs the Windows software that you need on Mac at home, in the office,... Read more
Tower 10.2.1 - Version control with Git...
Tower is a Git client for OS X that makes using Git easy and more efficient. Users benefit from its elegant and comprehensive interface and a feature set that lets them enjoy the full power of Git.... Read more

Latest Forum Discussions

See All

Pour One Out for Black Friday – The Touc...
After taking Thanksgiving week off we’re back with another action-packed episode of The TouchArcade Show! Well, maybe not quite action-packed, but certainly discussion-packed! The topics might sound familiar to you: The new Steam Deck OLED, the... | Read more »
TouchArcade Game of the Week: ‘Hitman: B...
Nowadays, with where I’m at in my life with a family and plenty of responsibilities outside of gaming, I kind of appreciate the smaller-scale mobile games a bit more since more of my “serious" gaming is now done on a Steam Deck or Nintendo Switch.... | Read more »
SwitchArcade Round-Up: ‘Batman: Arkham T...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for December 1st, 2023. We’ve got a lot of big games hitting today, new DLC For Samba de Amigo, and this is probably going to be the last day this year with so many heavy hitters. I... | Read more »
Steam Deck Weekly: Tales of Arise Beyond...
Last week, there was a ton of Steam Deck coverage over here focused on the Steam Deck OLED. | Read more »
World of Tanks Blitz adds celebrity amba...
Wargaming is celebrating the season within World of Tanks Blitz with a new celebrity ambassador joining this year's Holiday Ops. In particular, British footballer and movie star Vinnie Jones will be brightening up the game with plenty of themed in-... | Read more »
KartRider Drift secures collaboration wi...
Nexon and Nitro Studios have kicked off the fifth Season of their platform racer, KartRider Dift, in quite a big way. As well as a bevvy of new tracks to take your skills to, and the new racing pass with its rewards, KartRider has also teamed up... | Read more »
‘SaGa Emerald Beyond’ From Square Enix G...
One of my most-anticipated releases of 2024 is Square Enix’s brand-new SaGa game which was announced during a Nintendo Direct. SaGa Emerald Beyond will launch next year for iOS, Android, Switch, Steam, PS5, and PS4 featuring 17 worlds that can be... | Read more »
Apple Arcade Weekly Round-Up: Updates fo...
This week, there is no new release for Apple Arcade, but many notable games have gotten updates ahead of next week’s holiday set of games. If you haven’t followed it, we are getting a brand-new 3D Sonic game exclusive to Apple Arcade on December... | Read more »
New ‘Honkai Star Rail’ Version 1.5 Phase...
The major Honkai Star Rail’s 1.5 update “The Crepuscule Zone" recently released on all platforms bringing in the Fyxestroll Garden new location in the Xianzhou Luofu which features many paranormal cases, players forming a ghost-hunting squad,... | Read more »
SwitchArcade Round-Up: ‘Arcadian Atlas’,...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for November 30th, 2023. It’s Thursday, and unlike last Thursday this is a regular-sized big-pants release day. If you like video games, and I have to believe you do, you’ll want to... | Read more »

Price Scanner via MacPrices.net

Sunday Sale: Apple 14-inch M3 MacBook Pro on...
B&H Photo has new 14″ M3 MacBook Pros, in Space Gray, on Holiday sale for $150 off MSRP, only $1449. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8-Core M3 MacBook Pro (8GB... Read more
Blue 10th-generation Apple iPad on Holiday sa...
Amazon has Apple’s 10th-generation WiFi iPad (in Blue) on Holiday sale for $349 including free shipping. Their discount applies to WiFi models only and includes a $50 instant discount + $50 clippable... Read more
All Apple Pencils are on Holiday sale for $79...
Amazon has all Apple Pencils on Holiday sale this weekend for $79, ranging up to 39% off MSRP for some models. Shipping is free: – Apple Pencil 1: $79 $20 off MSRP (20%) – Apple Pencil 2: $79 $50 off... Read more
Deal Alert! Apple Smart Folio Keyboard for iP...
Apple iPad Smart Keyboard Folio prices are on Holiday sale for only $79 at Amazon, or 50% off MSRP: – iPad Smart Folio Keyboard for iPad (7th-9th gen)/iPad Air (3rd gen): $79 $79 (50%) off MSRP This... Read more
Apple Watch Series 9 models are now on Holida...
Walmart has Apple Watch Series 9 models now on Holiday sale for $70 off MSRP on their online store. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
Holiday sale this weekend at Xfinity Mobile:...
Switch to Xfinity Mobile (Mobile Virtual Network Operator..using Verizon’s network) and save $500 instantly on any iPhone 15, 14, or 13 and up to $800 off with eligible trade-in. The total is applied... Read more
13-inch M2 MacBook Airs with 512GB of storage...
Best Buy has the 13″ M2 MacBook Air with 512GB of storage on Holiday sale this weekend for $220 off MSRP on their online store. Sale price is $1179. Price valid for online orders only, in-store price... Read more
B&H Photo has Apple’s 14-inch M3/M3 Pro/M...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on Holiday sale this weekend for $100-$200 off MSRP, starting at only $1499. B&H offers free 1-2 day delivery to most... Read more
15-inch M2 MacBook Airs are $200 off MSRP on...
Best Buy has Apple 15″ MacBook Airs with M2 CPUs in stock and on Holiday sale for $200 off MSRP on their online store. Their prices are among the lowest currently available for new 15″ M2 MacBook... Read more
Get a 9th-generation Apple iPad for only $249...
Walmart has Apple’s 9th generation 10.2″ iPads on sale for $80 off MSRP on their online store as part of their Cyber Week Holiday sale, only $249. Their prices are the lowest new prices available for... Read more

Jobs Board

Senior Product Manager - *Apple* - DISH Net...
…Responsibilities** We are seeking an ambitious, data-driven thinker to assist the Apple Product Development team as our Wireless Product division continues to grow Read more
Senior Product Manager - *Apple* - DISH Net...
…Responsibilities** We are seeking an ambitious, data-driven thinker to assist the Apple Product Development team as our Wireless Product division continues to grow Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and offer a Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.