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

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - 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
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - 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

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter 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
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.