C++ Versus Objective-C

http://www.mactech.com/articles/mactech/Vol.13/13.03/CandObjectiveCCompared/index.html


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/>.


posted @ 2012-06-20 23:02  MXi4oyu  阅读(229)  评论(0编辑  收藏  举报