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

Latest Forum Discussions

See All

Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.