C and Objective C Compared
Volume Number: 13
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);