Objective-C: the More Flexible C++

An introduction to Objective-C for programmers familiar with C++ or any other OOP language.
Compiling the Samples

There are four major Objective-C compilers: Stepstone, GNU, Apple and Portable Object Compiler (POC). Stepstone and POC are preprocessors that emit vanilla C code. GNU and Apple are "native" compilers, creating intermediate code for the GNU code generator.

To compile the previous examples, enter:

gcc -Wno-import -c List.m
gcc -Wno-import -c List2.m
gcc -Wno-import -c main.m
gcc -o List  -Wno-import List2.o List.o main.o -lobjc -lpthread
Categories and Protocols

Categories compartmentalize a class definition or extend an existing one, possibly at runtime. They denote a set of method definitions that is segregated from the rest of the class definition.

Protocols allow you to organize related methods into groups. Protocol hierarchy is unrelated to class hierarchy. They are used to declare methods that others are expected to implement, declare the interface to an object while concealing its class and capture the similarities among classes that are not hierarchically related.

Protocols address the lack of multiple inheritance. They are equivalent to multiple inheritance for purely "abstract" classes. The closest you can get to multiple inheritance is to create a class with instance variables that are references to other objects. Instances can specifically redirect messages to any combination of the objects of which they are compounded. The Objective-C philosophy is that you do not need multiple inheritance because it creates more problems than benefits. Using protocols, one can have type-checking features without sacrificing dynamic binding. "Any object implementing messages in Protocol X is okay for this use" constrains the functionality and not the implementation or the inheritance.

@protocol Archiving
   -read: (Stream *) stream;
   -write: (Stream *) stream;
@end

and refer to it with:

/* MyClass inherits from Object and conforms to the
   Archiving protocol.  */
@interface MyClass: Object <Archiving>
@end

Example that spots incompatibility changes:

MyClass *obj1 = [MyClass new];
// OK: obj1 conforms to the Archiving protocol.
id <Archiving> obj2 = obj1;
// Error: obj1 does not conform to the TargetAction protocol.
id <TargetAction> obj3 = obj1;
Garbage Collection

Starting with version 0.9.0, GNUstep's libFoundation comes with two garbage-collecting mechanisms that provide you with the ability to solve memory management problems. libFoundation is a library that provides an almost complete implementation of the OpenStep specification, plus many other extensions that can be found in the newer versions of Rhapsody's (Mac OS X) Foundation.

From Unit-testing Frameworks a là extreme programming (XP) to XML parsers, one can take advantage of a large existing codebase. And if all fails, one can take advantage of the entire existing C code-base, as the GNUstep XML parser has demonstrated. It is an Objective-C wrapper around libxml.

We think that Objective-C is the better C++, which is really worth giving a try. GNUstep is extremely powerful.

An extended comparison of all the compilers discussed in this article can be found on our home page.

Resources

Simula

developer.apple.com/techpubs/macosx/Cocoa/ObjectiveC/ObjC.pdf

Foundation Library, Objective C API

libFoundation

Object-Oriented Programming and the Objective-C Language

FAQ

www.slip.net/~dekorte/Objective-C/Documentation/2_Comparisons/Comparisons.html

Articles on Objective-C by Brad Cox

Benchmarks for C++, Java and Objective-C by Sven Koehler

Ruby Bindings for GNUstep

Unit-testing framework

GNUstep XML Parser

Window Maker

Games Written in Objective-C

Objective-C Blocks

Object Oriented Programming in Objective-C

Objective C versus Smalltalk, C++ and Java

Compilers

GNU Compiler Collection

Portable Object Compiler

Books

Object Oriented Programming: An Evolutionary Approach. Brad J. Cox, Andrew J. Novobilski. Addison-Wesley, 1991.

Objective-C: Object Oriented Programming Techniques. Lewis J. Pinson, Richard S. Wiener. Addison-Wesley, 1991.

An Introduction to Object-Oriented Programming. 3rd Edition. Timothy A. Budd. Addison-Wesley, 2002.

Developing Business Applications With Openstep. N. Gervae. Springer Verlag Telos, 1996.

Openstep for Enterprises. Nancy Craighill. John Wiley & Sons, 1996.

Learning Cocoa. Apple Computer Technical Writers. O'Reilly, 2001.

Armin Roehrl (armin@approximity.com) and Stefan Schmiedl (stefan@approximity.com) lead the software company Approximity that optimises big distributed webventures.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Re: Objective-C: the More Flexible C++

dankelley's picture

Some thoughts from a scientist who also dabbles in software creation:

my 2 cents Canadian (not much in othe terms, lately) worth...

Some years ago, I wrote a pretty large (10^4 lines) open-source code

in C. It became apparent that it would help for this code to have

parts that were more object-oriented, and so I read a bit and decided

to convert those parts.

During this work, I learned that objC is quite beautiful. By that, I

mean that the code, and the logic it inspired, was elegant to the eye,

in the way that some mathematics proofs can be.

But one day I realized that none of the folks using this code knew

objective-C, whereas many of them knew C++. Since this was a shared

program, I wanted my users to be able to contribute to the work. And

so I started the process of converting the objective-C into C++. That

was not much fun, partly because the syntax is different and partly

because C++ seems not to inspire the writing of elegant code (or,

better stated, it seems not to inspire the construction of elegant

algorithms).

Why is this, exactly? I'm not sure. At first I thought my distaste

for C++ might be just a love of the old. But, now I've been using C++

for years, and I can read/write it much more easily than objective-C,

and I still feel the same way.

In summary, the advantage of objective-C seems to be that it inspires

an elegance of expression. The disadvantage is that fewer people can

read your code.

Of course, all of this may be moot, since it's my

understanding that many students are learning Java before they learn

any of the C dialects. Maybe I'm getting too old to keep up ... I

just get used to Perl and Python comes along like a knight in shining

armor, and before I learn it, I hear that now Ruby rules!

Dan.

Re: Objective-C: the More Flexible C++

Anonymous's picture

You're right. Obj-C done right is MUCH more elegant than anything else.

Of course, you have to get into the "mood" to do it right. Just applying the "old habits" (C++ etc.) won't work.

Where Objective-C shines is that it leads to truly reusable code. Just comparing the number of classes in a typical C++ library and within Objective-C shows that.

This is not surprising at all: most C++ or Java windowing libraries (like PowerPlant on Mac, MFC on Windows) are anyway just bad copies of the NextStep classes. Their quality only differs how much thought they put into the classes to reassemble the functionality of Objective-C in the choosen language.

so - why not choose the original first?

Learning the syntax is something like 2 days for a C programmer. The tough part is getting the own classes right. But once its understood, there is nothing like it anywhere.

I've written for 10 years in C and C++ and it was always messy and at the end no fun at all. After switching to Obj-C the only thing I regret is not buying a NextStep Station in the 90ies...

Michael

Objective-C---more than just games

WillAdams's picture

Macromedia FreeHand (v4) started as Altsys Virtuoso on NeXTstep.

Improv--Although there was an Improv 2 for Windows, it was never quite as nice

as Improv for NeXTstep (which also fell far short of where it ought to've

been), but there's still no widely available spreadsheet available now which

handles 3D data so elegantly AFAIK.

Then, one could compare the programs which are all but without peer, for

example TIFFany (PhotoShop on steroids), or PasteUp.app (developed almost

single-handedly by Glenn Reid in roughly a year). Or, MCI's Friends and Family

database system (they liked it so much, they bought the company!)

NeXTstep is also the premiere platform for using PostScript directly and

interactively---Alan Hoenig praises it in his book _TeX Unbound_

SoftMagic, www.softmagic.co.kr is an incredible product.

And of course, there's WebObjects....

Lastly, Tim Berners-Lee used NeXTstep (he crafted a thing called worldwideweb.app---guess what it

grew into)

William

Re: Objective-C: the More Flexible C++

Anonymous's picture

Hey, you cannot blame C++ for introducing new keywords and propose a language that overloads every special character on the planet :)

I dont want to say that Objective C is bad or something. But don't try to make a thing better by complaining about another thing.

Beside that, C++ is not only "C with Objects". It has many other useful features, like templates or references. Maybe it would be a good idea to think about mixing C++ and Objective C, creating a "Objective C++" that combines Objective C's runtime system with all the C++ features (and the more popular syntax of C++). As you can see, I am not a proponent of the 'make a language as simple as possible' school, but I rather prefer the 'add every single feature that can not be implemented in a lib, because every feature helps the programmer who works 100h a week in the damn language' school...

Re: Objective-C: the More Flexible C++

Anonymous's picture

Objective-C++ already exists! NeXT extended Objective-C in this way to leverage C++ into NeXTSTEP applications (if the solution already exists in C++ why not use that). It turns out that Objective-C++ is probably only useful for that purpose, the features in C++ have a heavy cost in readability and ease of use, so Objective-C++ isn't used much. Objective-C turns out to prove that K&R were right to keep C a small language. :-)

Re: Objective-C: the More Flexible C++

Anonymous's picture

As you can see, I am not a proponent of the 'make a language as simple as possible' school, but I rather prefer the 'add every single feature that can not be implemented in a lib, because every feature helps the programmer who works 100h a week in the damn language' school...

And it is thinking like that to cause C++ compilers to never be able to totally implement the C++ language specifications. The compiler makers have a hard time trying to implement these "features". I always get frustrated to write a program using valid C++ and it compiles and runs fine on one platform and try to compile it on another(VC++) and have either totally rewrite that part of code or do some conditional compilation that makes the code hard to read. I like C++ and wish a few of the very useful features like namespaces would be added to Objective-C. I am totally against templates being added since it is against the philosphy of a dynamic OO language.

A simpler language allows you to move on and start writing code to do some work. I was able to learn Objective-C in a few days and I understand the entire language. I been programming in C++ for 5 years and I still do not know the language.

Re: Objective-C: the More Flexible C++

Anonymous's picture

> I was able to learn Objective-C in a few days and I understand the entire language.

Just Understand the language is not enough, Apply them practical will tell.

> I been programming in C++ for 5 years and I still do not know the language.

Are you work as a professional programmer for a competitive company or non professional just writing some simple app as hobby or in goverment org that use & waste tax-payer money ?

Nowaday, all OOP similar to C++, include JAVA, C#, VB.NET etc. If you cannot understand C++, you cant understand thiese language as well.

If you are a professional programmer, esp in competitive company, you are already fired (for failed to know the language).

Other comment is, C++ Template (Now C#/VB dot.net also support similar features called "generic") is "good to have", but is NOT "must have", it can improve the reusability and flexibilty very much, esp like map, list, stack etc.(standard template library)
Nevertheless, You do NOT need to explicitly write C++ template to qualify as "C++ programmer". Many professional C++ programmer never write their own template. (template is not so easy to read, but very easy to use).

Many developer likes to make use of some language features just purely because of "the language have this features - I MUST use it", or to show-case there are the pro. , without considering practically, case by case suitability and portability. (ie, "good to have" vs "must have").

Not using template, does not disqualify you as C++ Programmer, But Not even have a basic understand of it, may disqualify you as C++ programmer).

What language to use, and their understanding of the language, depend on the programmer computer-science knowledge also, of-course we cannot expect, for someone study archeology to code in C++. But for those have strong Computer-Science background, C++ is just as easy as A B C.

BTW, I self study OOP generally, C++ specifically. (my school deos not not teach us C++ at that time). I can "understnad" it in few days also, cannot imaging there is someone cannot understand it after 5 years !

Re: Objective-C: the More Flexible C++

Anonymous's picture

Objective C++ already "exists"...

Re: Objective-C: the More Flexible C++

Anonymous's picture

And this does not look like C.

No wonder people adopt C++ instead of Objective-C.

Re: Objective-C: the More Flexible C++

Anonymous's picture

In my opinion, part of C++'s problem is that it looks TOO MUCH like C. This, I think, encourages confusion among beginners and the tendency to write C code, not OO code, with C++.

IMHO, a method call is inherently different from a function call - especially in a dynamic system like ObjC, and should have its own notation distinct from that of a function call.

Likewise, an object is inherently different from a structure, and the notation should be different. Etc.

I much prefer ObjC's [foo bar:1 with:me];

syntax, because it is quite clear that this is an OO construct, and different from all the C code that might surround it.

Without OOP knowledge, not look too much like.

Anonymous's picture

> In my opinion, part of C++'s problem is that it looks TOO MUCH like C. This, I think, encourages confusion among beginners and the tendency to write C code, not OO code, with C++.

Programmer without OOP concept and skill, will write in structured manner given whatever OOP language to them.

for eg, if the code is written by non OOP/C++ programmer, there actually write in 'C' only, wrapped, or saved in .cpp or .cc files.

.cpp or .cc save file does NOT mean it is C++ code. keep in mind.

For those programmer, There are not C++ beginners, but OOP beginner or totally have no idea of what is OOP.

If you given them Obj-C capable compiler, there will also write their code in C only code, wrapped / saved in .m files - nothing to do with "look too much like".

Re: Objective-C is definitely superior to C++

Anonymous's picture

I totally agree with you...

Who does not agree with the title either does not know the language or is a moron (no pun intended)

On the other hand, I believe Objective-C lacks a couple of important features that C++ has (namespaces and templates among them), but I found that it is still an excellent language even without those...

P.S.

You can always mix both languages with Objective-C++

Once I read an article by Tim Sweeney (creator of UT) where he analysed programming languages (or something like that)... he stated that in the future, languages will have features to make class hierarchies "extensible" (I can't remember the exact words)... Obj-C is already capable to do that and with trivial effort (and dynamically: you can "override" any class you find with your own version)

Re: Objective-C: the More Flexible C++

Anonymous's picture

why don't your use [[List alloc] init] to create an object? You used [List new]. But you said:

Usually, you create objects with a call to alloc:

Very confusing.

Re: Objective-C: the More Flexible C++

Anonymous's picture

new is a short cut.

[Object new]

is equivalent to

[[Object alloc] init]

Re: Objective-C: the More Flexible C++

Anonymous's picture

new is just a "shorthand" method used in GNUStep:

- (id) new

{

return [[self alloc] init];

}

Method new might not actually be (not sure) the one above but surely it does the same as above (conceptually)

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState