TweetFollow Us on Twitter

Think C Tutor
Volume Number:5
Issue Number:10
Column Tag:MacOOPs!

A First Look At THINK C 4.0

By Alastair Dallas, Glendale, CA

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Think C 4.0 First Look

[Alastair Dallas is the president of Software Magic, a developer of (as yet unreleased) Macintosh software. He moonlights as a Sr. Software Designer for the IBM PC side of Ashton-Tate, publisher of FullWrite Professional, Full Impact and dBASE Mac, none of which Mr. Dallas had anything to do with.]

If you are like me, you were surprised by Symantec’s announcement at the end of July that a brand new, object-oriented version of their popular C compiler would be available soon. Rumors that principal author Michael Kahl was working on object-oriented extensions to his LightspeedC package predate the June, 1988 release of version 3.0. When Apple warned us this spring that “you’d better learn object-oriented programming” if you want to program your Mac in the future, perhaps you, like me, were hoping for an object-oriented programming system (oops) that was as accessible as THINK’s LightspeedC to learn with.

THINK C (they dropped the name Lightspeed with this release) is nearly the C version of MacApp we’ve been waiting for. The new version supports Object Pascal-style extensions and a generic application which you can customize. And it’s available now. Symantec must have waited until THINK C 4.0 was ready to ship before announcing it, because my upgrade order was filled in less than a week-much faster than the upgrade to 3.0. The upgrade price is $69 to registered owners, and the retail price of 4.0 is said to be over 50% higher than 3.0.

What do you get for your money? A lot. In addition to the popular integrated compiler, linker, editor, source-level debugger and make facility, this release includes version 1.0 of the THINK Class Library (TCL) which encapsulates most of the standard Macintosh user interface. The C compiler includes improvements making it 95% conformant with the draft ANSI C standard as well as object-oriented extensions which make the THINK Class Library possible.

THINK C 4.0 arrives on four disks, including full source code to a 100% ANSI-conformant library, Macintosh ROM Toolbox “glue” libraries, several example programs (non-oops examples from 3.0 and Art Class, a fairly full-featured MacPaint-type application written using TCL), and template projects (Starter and Pedestal) which you can use to build your own applications.

Two soft-cover books describe the product. The 512-page User’s manual is essentially the 3.0 user’s manual with 250 pages of object-oriented material added as section four. The 37 Core Classes of the TCL are described here, one to a chapter. While the size of the other book, the Standard Libraries Reference, is about the same as it was in 3.0, the content has changed profoundly because the functions and header files are now organized according to the ANSI standard.

If you are familiar with version 3.0, you’ll want to hear exactly what’s new about 4.0:

• Object extensions to C (described below)

• THINK Class Library (almost MacApp for C)

• ANSI C compatibility

• Prototypes for function definitions

• # (stringize) and ## (concatenate) preprocessor operators

• long double type, long double literals

• ANSI standard library w/ glass tty example

• Inline assembler extensions for 68020 and 68881 instructions

• “Once-only” headers

• Multi-segment code resources

• Better cdev (control panel device) support

• Inline assembler functions (makes glue functions more efficient)

Introduction to Object-Oriented Programming

The lecturer at a recent seminar explained that if he wanted to sell his cat just now (to a bunch of programmers), he would advertise it as an object-oriented cat. Object-oriented, the buzzword, has been around since the late 1970s, when BYTE magazine broke the story about Smalltalk (which, legend has it, got Steve Jobs interested in Xerox PARC in the first place).

The term object-oriented may be used to describe almost anything, including a cat, but it almost always promises reusable code. THINK C (TC) is no exception; the system makes it easy to take a generic piece of code and customize it by overriding one or more of its functions. Once you customize the generic window code so that sizing the window maintains its aspect ratio (width / height), you then have a new type of generic window object that you can specialize in other ways for your next project.

Objects are a way of grouping data together with the functions which manipulate that data. All the books tell you that objects mimic the real world, but I think a better example is that objects mimic Macintosh user interface elements. Take windows, for example. A window object has data (the WindowRecord, which includes a grafPort, and perhaps some other variables) and it has certain operations it knows about. These operations are called methods in the literature, but they’re implemented as functions in THINK C. For example, a window can change size, move (drag), hide, show and so on. An application might have several windows, each capable of the same operations, but each window would have a different WindowRecord.

In THINK C, you essentially address the WindowRecord (actually the Window object) and say “hide yourself.” THINK C knows how to find the functions which all Window objects have in common. If you want to customize the Window object as I described above, for example, you create a new object type (called a class) that is derived from the Window class with, in this case, a special “change size” function. If you tell your special Window to do something ordinary like hide itself, THINK C will use the same function that any Window would use for that command-your special Window object only provides the code that makes it different from a normal Window.

For more reading about object-oriented concepts as they apply to the Macintosh, I recommend “Object-Oriented Programming for the Macintosh” by Kurt Schmucker (Hasbrouck Heights, NJ:Hayden, 1986, ISBN 0-8104-6565-5). This book emphasizes MacApp, but describes the Macintosh user interface in object-oriented terms and provides an overview of several oops languages as well, such as Lisa Clascal, Smalltalk and Objective-C.

The most famous object-oriented C is described in “The C++ Programming Language” by Bjarne Stroustrup (Reading, MA:Addison-Wesley, 1986, ISBN 0-201-12078-X). The THINK C manual (p. 9) claims that THINK’s syntax resembles C++ and states that “The extensions are upward-compatible with C++ (i.e., C++ compilers can compile THINK C programs, but THINK C cannot compile all C++ programs).” Because C++ is a superset of the C language, this statement is strictly true, but it is misleading to consider THINK C an implementation of C++. C++ v1.0 implemented several concepts which THINK C left out, and C++ v2.0 has just been released with even more features. The following C++ features are not implemented in THINK C:

• Operator overloading (the ability to define operators like ‘+’ in the context of a particular object)

• Special automatic constructor and destructor methods (all calls are explicit in TC)

• Public vs. private class variables and methods (all are public in TC)

• Friend functions for access to private variables

• Virtual functions

• Inline code expansion (functions defined within class definitions)

• The // characters start a comment that extends to end of the line

• Multiple inheritance (C++ v2.0)

THINK C reserves no new keywords. Instead, identifiers indirect, direct, this and inherited are “interpreted specially in context.” In contrast, C++ programs use the following reserved words:

class

delete

friend

inline

new

operator

overload

public

this

virtual

Like C++, THINK C uses structures for class definitions; methods use the ‘::’ scope resolution operator, as in “myClass::myMethod”; and objects can reference themselves using “this.”

Although on the surface THINK C could be called “C++ Lite,” the two languages are more alike than, say, C and Smalltalk. And the implementation of THINK C is “close to the machine,” in that it was designed specifically to make programming a Macintosh efficient, rather than to satisfy purist notions of language design.

Object Extensions to THINK C

In conventional C, a data structure may be defined without creating a variable or reserving storage space; multiple variable declarations can then reference this structure definition. The structure is an abstract definition and the variables are concrete instances. In THINK C, objects are much the same.

An abstract description of an object is called a class. A class is a structure definition containing variables and functions, as in:

/* 1 */

struct classname : superclass
 
 /* instance variables */
 int myVar; /* for example */
 char myStr[255];
 Rect bounds;

 /* by convention, methods follow instance variables */
 void Init(void);
 void Destroy(void);
 Boolean Hit(Point where);

Superclass is the class from which this class is derived, such as CObject using TCL (root classes have superclass direct or indirect, described in more detail in the manual). The classname can be used without the keyword struct, because THINK C thoughtfully assumes that you want:

typedef struct classname classname

Objects are specific instances of a class. Objects are usually implemented as handles (direct root objects and their descendants are pointers), but THINK C adds an automatic level of indirection for you, so that you declare objects as pointers, and reference their members with the ‘->’ operator:

classname *object;

object->method(myPt);

The file <oops.h> declares functions which act on objects in general: new() creates a new instance of an object class; delete() disposes of an instance; member() tests whether a particular object is a member of a specified class; and bless() assigns an object (loaded externally from a resource, for example) to a particular class.

Any methods (functions) declared for a class must be defined using syntax like:

Boolean classname::Hit (Point where)
 
 return (PtInRect(where, &bounds));

Note that in this example, bounds is an instance variable of this object-THINK C provides an implicit declaration. The variable this is implicitly declared, as well, to allow an object’s methods to refer to themselves. Minimizing global variables is an important part of making code reusable, and objects encourage this practice.

The THINK Class Library

THINK C 4.0 includes a set of predefined classes which implement the standard Macintosh user interface. The 37 Core Classes are described in the User’s Manual. A few highlights (class names begin with ‘C’ by convention):

CApplication - top of the chain of command, supervises documents

CDocument - “the essence of a Macintosh application,” manages a file and a window

CSwitchboard - routes events to all objects

CBartender - handles menu choices (and menuKeys)

CBureaucrat - implements a “chain of command” starting with the current gopher (usually a part of a window). Each link in the chain, like all good bureaucrats, passes anything it doesn’t understand up the chain to its supervisor.

CWindow - handles a window, consisting of one or more panes

CPane - part of a window, e.g., content, scroll bar, grow box, etc.

CPanorama - a scrollable pane (it’s actually a little more complicated-more object classes are involved)

CChore - background or urgent tasks

TCL goes considerably beyond menus, windows and documents. The library (actually a template application) supports printing, file I/O, show/hide clipboard, pictures and editable text. It even makes Undo fairly easy to implement, because each command is an integer and the chain of command is unambiguous.

TCL was apparently entirely written by Gregory H. Dow, who also wrote the Art Class example program. To implement some of the trickier features of Art Class, he extended the Core Classes of TCL and Symantec provides source code to these extensions (More Classes), as well. Although they didn’t make it into the user’s manual, More Classes include:

CTearOffMenu - how much would you pay to avoid figuring these out? But wait, before you answer-you also get...

CSelectorMDEF - supports custom tool and pattern menus

CPictFile - reads, writes MacDraw™ (PICT) files

CPNTGFile - reads, writes MacPaint™ files

CBitMap - displays bitmaps (CBitMapPane makes them scrollable)

CColorWindow - color windows

The beauty of the TCL (and MacApp) is that your application is reduced to the elements which make it distinct from a standard application. It’s no longer necessary to ferret out the specifics by wading through pages of event loop and DoContentClick() code. The main() function of any program using TCL looks something like:

/* 2 */

#include <CApplication.h>

extern CApplication *gApplication;

void main()
 
 gApplication = new(CYourApp);
 ((CYourApp *) gApplication)->IYourApp();

 gApplication->Run();
 gApplication->Exit();

 /* main */

A Simple Example

The manual recommends that your classes (you must override certain classes, such as CApplication) be defined in a “.h” file and implemented in a “.c” file each with the name of the class. That is, a typical project might include:

app.c
CmyApp.c, CmyApp.h
CmyDoc.c, CmyDoc.h

This convention makes a lot of sense and encourages reuse of common classes in multiple projects. However, it means looking at a lot of files in the beginning when you’re trying to figure out how it all works.

On the theory that more than one sort of example helps the learning process-you have to see anything from more than one side to understand it-I’ve written a really simple program using TCL which does far less than the templates provided with THINK C. I’ve grouped the code into one module, too, so that you can see the extent of it.

This example leans on TCL to provide a standard Macintosh application which puts up a window (not a document). TCL implements desk accessories, dragging and sizing the window, MultiFinder support and one command: Quit.

It was necessary to define three new classes: CTutorApp, CTutorDir and CTutorWindow. The standard TCL classes CApplication and CDirector are called abstract classes because they are not pre-implemented and must be overridden (in C++ terms, they are virtual), so we implement our own initialization methods for them.

CTutorApp::ITutorApp calls the standard CApplication::IApplication() function with some boilerplate memory constraints and creates and initializes an instance of CTutorDir, which will control our window.

CTutorDir::ITutorDir calls the standard CDirector::IDirector() function and passes the address of our application object (gApplication) as supervisor. Then it creates and initializes an instance of CTutorWindow.

The only method we override in the standard CWindow class is Close(). We do this so that clicking in the close box of the window will have the effect of Quitting the application. Our CTutorWindow::Close() function performs the window close task by calling inherited::Close() first, and then sends the message Quit() to our application, which performs several shutdown tasks and ends up returning from the Run() function. Our main() then calls gApplication->Exit() to tell our application that we’re really leaving now and finally exits to shell by falling off the end of main().

To compile this application, I “borrowed” a copy of the Pedestal project resource file. Using ResEdit, I changed the MENU resource for the File menu so that only the Quit item remained, and I set the title of the WIND 2000 resource to “Mac Tutor Class Act.” Using a copy of the Pedestal project folder, I included most of the THINK Class Library as separate files, and THINK C did the rest.

Conclusion

If you want to write programs for the Macintosh, you will have to become familiar with object-oriented programming techniques. It makes sense for a lot of reasons, not the least of which is that Apple is warning developers that oops is a prerequisite to many of the things they’re working on. The Macintosh interface is just too complicated to let reinventing the wheel get in the way of writing insanely great applications.

Until now, the only mainstream way to get the benefits of oops was to buy the Macintosh Programmer’s Workshop, buy MacApp and learn to program in Object Pascal. Apple will eventually offer MPW C++ and they plan to offer MacApp for C++ as well. Standards, especially those promulgated by Apple, are a very good thing. But LightspeedC became a de facto standard by being “firstest with the mostest,” and the same could happen with the THINK Class Library. Meanwhile, everything is converging, anyway-MacApp is being ported to C, THINK Pascal will support MacApp eventually, and so on.

The point is, there is no reason to wait for object-oriented programming to come to you. The time is now to dive in and get used to the new programming paradigm. I have seen the future, and it’s object-oriented.

/* MacTutor.c */
#include <CApplication.h>
#include <CDesktop.h>
#include <CDirector.h>
#include <commands.h>

struct CTutorApp : CApplication
 {
 /* no instance variables */
 /* instance methods */
 void ITutorApp(void);
 void DoCommand(long theCommand);
 };
 
struct CTutorDir : CDirector
 {
 /* CDirector is an abstract class, so we must override it */
 void ITutorDir(void);
 };

struct CTutorWindow : CWindow
 {
 /* want to override close for our own nefarious purposes */
 void Close();
 };

extern CApplication *gApplication;
extern CDesktop *gDesktop;

void main(void)
{
 gApplication = new(CTutorApp);
 ((CTutorApp*)gApplication)->ITutorApp();

 gApplication->Run();
 
 gApplication->Exit();  
}/* main */

void CTutorApp::DoCommand(long theCommand)
{
 /* not strictly necessary-here in case we ever want to handle a command 
*/
 switch (theCommand)
 {
 
 default:
 inherited::DoCommand(theCommand);
 break;
 
 } /* switch */
 
 return;
}/* CTutorApp::DoCommand */

void CTutorApp::ITutorApp()
{
 CTutorDir *ourDirector;

 CApplication::IApplication(4, 20000L, 2000L);
 
 ourDirector = new(CTutorDir);
 ourDirector->ITutorDir();
 
 return;
}/* CTutorApp::ITutorApp */

void CTutorDir::ITutorDir()
{
 CDirector::IDirector(gApplication);
 
 itsWindow = (CWindow *) new(CTutorWindow);
 itsWindow->IWindow(2000, FALSE, gDesktop, this);
 
 return;
}/* CTutorDir::ITutorDir */

void CTutorWindow::Close(void)
{
 inherited::Close();
 gApplication->Quit();
 
 return;
}/* CTutorWindow::Close */

/* EOF: MacTutor.c */

 
AAPL
$105.22
Apple Inc.
+0.39
MSFT
$46.13
Microsoft Corpora
+1.11
GOOG
$539.78
Google Inc.
-4.20

MacTech Search:
Community Search:

Software Updates via MacUpdate

Ember 1.8.2 - Versatile digital scrapboo...
Ember (formerly LittleSnapper) is your digital scrapbook of things that inspire you: websites, photos, apps or other things. Just drag in images that you want to keep, organize them into relevant... Read more
Tonality Pro 1.1.2 - Professional-grade...
Tonality Pro gives you the power to create stunning and dramatic black & white images. This is a complete monochrome image editor with more than 150 one-click style presets, totally unique... Read more
VueScan 9.4.49 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
OS X Server 4.0 - For OS X 10.10 Yosemit...
Designed for OS X and iOS devices, OS X Server makes it easy to share files, schedule meetings, synchronize contacts, develop software, host your own website, publish wikis, configure Mac, iPhone,... Read more
TotalFinder 1.6.12 - Adds tabs, hotkeys,...
TotalFinder is a universally acclaimed navigational companion for your Mac. Enhance your Mac's Finder with features so smart and convenient, you won't believe you ever lived without them. Tab-based... Read more
BusyCal 2.6.3 - Powerful calendar app wi...
BusyCal is an award-winning desktop calendar that combines personal productivity features for individuals with powerful calendar sharing capabilities for families and workgroups. BusyCal's unique... Read more
calibre 2.7 - Complete e-library managem...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more
Skitch 2.7.3 - Take screenshots, annotat...
With Skitch, taking, annotating, and sharing screenshots or images is as fun as it is simple.Communicate and collaborate with images using Skitch and its intuitive, engaging drawing and annotating... Read more
Delicious Library 3.3.2 - Import, browse...
Delicious Library allows you to import, browse, and share all your books, movies, music, and video games with Delicious Library. Run your very own library from your home or office using our... Read more
Art Text 2.4.8 - Create high quality hea...
Art Text is an OS X application for creating high quality textual graphics, headings, logos, icons, Web site elements, and buttons. Thanks to multi-layer support, creating complex graphics is no... Read more

Latest Forum Discussions

See All

Rami Ismail Opens Up distribute​() for D...
Rami Ismail Opens Up distribute​() for Developers Posted by Jessica Fisher on October 24th, 2014 [ permalink ] Rami Ismail, Chief Executive of Business and Development at indie game studio | Read more »
Great Hitman GO Goes on Sale and Gets Ne...
Great Hitman GO Goes on Sale and Gets New Update – Say That Three Times Fast Posted by Jessica Fisher on October 24th, 2014 [ permalink ] | Read more »
Rival Stars Basketball Review
Rival Stars Basketball Review By Jennifer Allen on October 24th, 2014 Our Rating: :: RESTRICTIVE BUT FUNUniversal App - Designed for iPhone and iPad Rival Stars Basketball is a fun mixture of basketball and card collecting but its... | Read more »
Rubicon Development Makes Over a Dozen o...
Rubicon Development Makes Over a Dozen of Their Games Free For This Weekend Only Posted by Jessica Fisher on October 24th, 2014 [ permalink ] | Read more »
I Am Dolphin Review
I Am Dolphin Review By Jennifer Allen on October 24th, 2014 Our Rating: :: NEARLY FIN-TASTICUniversal App - Designed for iPhone and iPad Swim around and eat nearly everything that moves in I Am Dolphin, a fun Ecco-ish kind of game... | Read more »
nPlayer looks to be the ultimate choice...
Developed by Newin Inc, nPlayer may seem like your standard video player – but is aiming to be the best in its field by providing high quality video play performance and support for a huge number of video formats and codecs. User reviews include... | Read more »
Fighting Fantasy: Caverns of the Snow Wi...
Fighting Fantasy: Caverns of the Snow Witch Review By Jennifer Allen on October 24th, 2014 Our Rating: :: CLASSY STORYTELLINGUniversal App - Designed for iPhone and iPad Fighting Fantasy: Caverns of the Snow Witch is a sterling... | Read more »
A Few Days Left (Games)
A Few Days Left 1.01 Device: iOS Universal Category: Games Price: $3.99, Version: 1.01 (iTunes) Description: Screenshots are in compliance to App Store's 4+ age rating! Please see App Preview for real game play! **Important: Make... | Read more »
Toca Boo (Education)
Toca Boo 1.0.2 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0.2 (iTunes) Description: BOO! Did I scare you!? My name is Bonnie and my family loves to spook! Do you want to scare them back? Follow me and I'll... | Read more »
Intuon (Games)
Intuon 1.1 Device: iOS Universal Category: Games Price: $.99, Version: 1.1 (iTunes) Description: Join the battle with your intuition in a new hardcore game Intuon! How well do you trust your intuition? Can you find a needle in a... | Read more »

Price Scanner via MacPrices.net

Weekend sale: 13-inch 128GB MacBook Air for $...
Best Buy has the 2014 13-inch 1.4GHz 128GB MacBook Air on sale for $849.99, or $150 off MSRP, on their online store. Choose free home shipping or free local store pickup (if available). Price valid... Read more
Nimbus Note Cross=Platform Notes Utility
Nimbus Note will make sure you never forget or lose your valuable data again. Create and edit notes, save web pages, screenshots and any other type of data – and share it all with your friends and... Read more
NewerTech’s Snuglet Makes MagSafe 2 Power Con...
NewerTech has introduced the Snuglet, a precision-manufactured ring designed to sit inside your MagSafe 2 connector port, providing a more snug fit to prevent your power cable from unintentional... Read more
Apple Planning To Sacrifice Gross Margins To...
Digitimes Research’s Jim Hsiao says its analysts believe Apple is planning to sacrifice its gross margins to save its tablet business, which has recently fallen into decline. They project that Apple’... Read more
Who’s On Now? – First Instant-Connect Search...
It’s nighttime and your car has broken down on the side of the highway. You need a tow truck right away, so you open an app on your iPhone, search for the closest tow truck and send an instant... Read more
13-inch 2.5GHz MacBook Pro on sale for $949,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $949.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $150 off MSRP. Price is... Read more
Save up to $125 on Retina MacBook Pros
B&H Photo has the new 2014 13″ and 15″ Retina MacBook Pros on sale for up to $125 off MSRP. Shipping is free, and B&H charges NY sales tax only. They’ll also include free copies of Parallels... Read more
Apple refurbished Time Capsules available sta...
The Apple Store has certified refurbished Time Capsules available for up to $60 off MSRP. Apple’s one-year warranty is included with each Time Capsule, and shipping is free: - 2TB Time Capsule: $255... Read more
Textilus New Word, Notes and PDF Processor fo...
Textilus is new word-crunching, notes, and PDF processor designed exclusively for the iPad. I haven’t had time to thoroughly check it out yet, but it looks great and early reviews are positive.... Read more
WD My Passport Pro Bus-Powered Thunderbolt RA...
WD’s My Passport Pro RAID solution is powered by an integrated Thunderbolt cable for true portability and speeds as high as 233 MB/s. HighlightsOverviewSpecifications Transfer, Back Up And Edit In... Read more

Jobs Board

*Apple* Solutions Consultant - Apple Inc. (U...
…important role that the ASC serves is that of providing an excellent Apple Customer Experience. Responsibilities include: * Promoting Apple products and solutions Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.