TweetFollow Us on Twitter

December 92 - BE OUR GUEST

BE OUR GUEST

COMPONENTS AND C++ CLASSES COMPARED

DAVID VAN BRINK

[IMAGE 037-040_Van_Brink_rev1.GIF]

If you're familiar with C++ classes but new to thinking about components, you may find it instructive to know how the two compare. Although each has its own niche in Macintosh software development, components and C++ classes have many features in common.

In general, both components and C++ classes encourage a building-block approach to solving complex problems. But whereas a component is separate from any application that uses it, a class exists only within the application that uses it. Components are intended to add systemwide functionality, while classes are intended to promote a modular approach to developing a program.

We can also compare components and C++ classes in terms of how they're declared and called, their use of data hiding and inheritance, and their implementation. But first, let's briefly review what a class is and what a component is.

SOME BASIC DEFINITIONS
A class, in the programming language C++, is a description of a data structure and the operations (methods) that can be performed on it. An instance of a class is known as an object. Classes are provided in C++ to promote an "object-oriented programming style." By grouping a data type and its methods together, classes enable programmers to take a modular approach to developing a program.

A component, as described in the preceding article ("Techniques for Writing and Debugging Components"), is a single routine that accepts as arguments a selector and a parameter block. The selector specifies which of several (or many) operations to perform, and the parameter block contains the arguments necessary for that operation. Components are "registered" with the Component Manager and can be made available to either the program that registered the component or to any program that's executed, making it possible to add systemwide functionality. For instance, if Joe's Graphics Corporation develops a new image compression technique, it can be sold to users as a component. Users install the component simply by dragging an icon into a folder, and that form of image compression is then automatically available to all programs that make use of graphics.

DECLARING CLASSES AND COMPONENTS
A C++ class is declared in much the same way as a struct, with the addition of routines that operate only on the structure described. Once the class is declared, instances can be declared in exactly the same way as other variables. That is, to create an instance of a class, you either declare a variable of that class or dynamically allocate (and later deallocate) a variable of that class.

A component must be registered with the Component Manager. At that time, its type, subtype, manufacturer, and name are specified. The type, subtype, and manufacturer are long integers; the name is a string. Component instances can only be created dynamically, using specific Component Manager routines. To create an instance of a component that has been registered, a program must first find the component. If the seeking program is the same one that registered the component, it already has the component. If not, it can make Component Manager calls to search for all available components with a given type, subtype, and manufacturer; any part of the description can be a wild card.

Once a component has been found, it must be opened, and this operation produces a reference to the component instance. Operations can be performed on the component instance using this reference.

Table 1 compares how classes and components are declared and how instances of each are created. (Note that for components, the code is idealized.)

CALLING ALL ROUTINES
Calling a routine that operates on a C++ object is slightly different from making a standard routine call: the call more closely resembles a reference to an internal field of a struct. The routine that gets called is identical to any other routine, except that it's declared within the class definition rather than at the same brace level as the main routine.

Calling a component routine is identical to calling any other routine. The first argument is always the component instance, and other arguments may optionally follow. The return type of every component routine is a long integer, and part of the numerical range is reserved for error messages from either the component or the component dispatch mechanism.

The Component Manager lets a program issue calls to a component that it has never "met" before. This form of dynamic linking is crude, because no type checking is performed.

Table 1 compares how classes and components are called.

DATA HIDING
A C++ class can have "private" fields and methods, which are accessible by class methods but not by the caller. The programmer can see these private parts simply by perusing the class declaration. If a change to the implementation of a class requires that the private parts be changed, relinking with the implementation of the class won't be sufficient: all clients must be recompiled, since the positions of public fields might have changed. (One tricky way around this is to include a private field of type char * that's really a pointer to the class's internal state data. The class constructor allocates memory for whatever internal state it likes and coerces a pointer to it to live in that char * field. This technique is useful for object-only software library distribution and also protects proprietary algorithms from curious programmers.)

A component is responsible for allocating memory for its internal state (the component's "globals") when it's opened and releasing that memory when it's closed. There are both component globals and component instance globals. These correspond to static and automatic variables in a C++ class and have similar utility. A component might keep track of how many instances of itself have been opened and restrict that number by failing on the open call.

INHERITANCE
It's often useful to build software on top of existing functionality or, alternatively, to take existing functionality and alter it to perform a more specialized function. Both of these things can be accomplished for C++ classes with inheritance. In the former case, the new class will have methods that don't exist in the base class; in the latter, the new class will have methods with the same name as methods in the base class but that take precedence over the base methods.

Components and the Component Manager support both kinds of inheritance as well, as discussed in the preceding article. All components of a given type must support the same set of calls, although this is enforced only by convention. Components of a particular type and subtype may optionally support other calls as well, and components of a particular type, subtype, and manufacturer may support still more calls. In the case where a component wants to use the services of another component and perhaps override some of its functions with modifications, Component Manager utilities let a component designate another component as its "parent." A simple protocol ensures that the correct variant of a routine gets called. When a component must call itself, it must issue the call to its child component, if any. When a component wants to rely on the existing implementation of the parent component, it must pass the call to its parent.

IMPLEMENTING CLASSES AND COMPONENTS
My discussion of implementation is based on the 68000 platform, since that's the only one I've scrutinized with regard to compiled C++ and Component Manager calls.

The routines that can be used with a C++ class are declared, and optionally implemented, within the class declaration. They behave like normal C routines, as described earlier.

A call to a C++ class that has no parents or descendants is compiled as a direct subroutine call, exactly as is a standard routine call. A call to a C++ class that has parents or descendants is slightly more complicated. A table lookup is used at run time to determine exactly which implementation of a routine gets called for the particular object being operated on. Such a call takes perhaps a dozen assembly instructions.

A component consists of only a single routine. It's passed a selector and a parameter block. The selector is used to decide which operation to actually perform, and the parameter block contains all the arguments passed by the caller.

The component's parameter block is untyped -- the component routine has no way to determine what kinds of arguments were originally passed, and herein lies the danger. Some languages, such as LISP, have untyped arguments; in LISP, however, a routine can determine how many arguments have been passed and what the argument types are. A component interface is more like assembly language -- or C without prototypes! -- in that it can determine nothing about what has been passed to it.

You can't compile a C++ program containing a call to a nonexistent routine; the compiler will balk. (Well, OK, this isn't strictly true: there are dynamically linking systems for C++, and other languages, that let you call a C++ routine that hasn't been linked with the rest of the compiled source code; the routine can be linked to later, at run time. But no facility of this type is currently standard in the Macintosh Operating System or supported under the standard Macintosh development tools.) In the case of components, the compiler can't check for such illegal calls, since the particular components that may be opened are decided at run time. Therefore, the caller must be prepared to handle a "Routine Not Implemented" error if a call is made with an unknown selector.

All calls to components pass through the Component Manager's dispatch mechanism. The dispatcher must locate the component's entry point and globals from the component reference, which is not simply a pointer but a packed record containing an index into a table and some bits used to determine whether the component reference is still valid. If a client makes a call to a component it no longer has open, the Component Manager has a statistical likelihood of catching this call and returning an appropriate error.

The Component Manager has facilities to redispatch the parameter block to one of many routines, and those routines are written to take the arguments as originally passed. The Component Manager was originally written for use on the 68000 series of processor; on computers with that processor, the parameter block doesn't have to be recopied onto the stack for further dispatching. On other processors the parameters might have to be recopied, however.

The Component Manager has been highly optimized and fast dispatching can reduce its overhead still more, but in general its lookup-and-dispatch process still takes several dozen instructions. If the component being called is using the Component Manager's inheritance mechanism, further overhead is incurred by passing control to the parent or child component. Overall, the Component Manager is quite efficient, but still not as efficient as direct routine calls. Table 1 compares how classes and components are implemented.

IN SUM
Components, as supported by the Component Manager, exhibit many of the features of C++ classes. Both encourage a modular approach to solving problems. Both feature inheritance and data hiding. Where they differ is in how they're declared and implemented, how they do (or fail to do) type checking, and how expensive they are to call. Each occupies its own distinct niche in Macintosh programming: classes as a way to ease development of a single program, components as a way to add systemwide functionality and give control and choice to the user.


Table 1A Comparison of Calls: Classes (Actual Code) Versus Components (Idealized Code)

Declaring a Class

class MyClass {
/* Variables and methods for 
    the class */
}

Declaring a Component

myComponent = RegisterComponent(MyEntryRoutine,
        myType, mySubType, myManufacturer, "A Component");

Creating a Class Instance

MyClass x;

Creating a Component Instance

myComponent= FindComponent(myType, mySubType, myManufacturer);
myInstance = OpenComponent(myComponent);

Calling a Class

x.MyMethod(arg1, arg2);

Calling a Component

result = MyMethod(myInstance, arg1, arg2);

Implementing a Class

class MyClass {
    void MyMethod(int arg1, int arg2) {
    /* Some code for MyMethod */
    }
}

Implementing a Component

long MyEntryRoutine(ComponentParams *params, char *globals) {
    switch(params->selector) {
        case kOpen:
        case kClose:
            return noErr;
        . . . /* other required calls here */
        case MyMethod:
        /* Do my method. */
        /* arg1 and arg2 are in params. */ return noErr;
        default:
            return routineNotImplementedErr;
    }
}

DAVID VAN BRINK is a computer programmer. When he's not busy programming computers, he can usually be found writing computer programs. Mostly, he does this in the soothing fluorescent glow of his cubicle at Apple. He's presently writing components (with great fervor) to support musical synthesizers for QuickTime. *

We welcome guest columns from readers who have something interesting or useful to say. Send your column idea or draft to AppleLink DEVELOP or to Caroline Rose at Apple Computer, Inc., 20525 Mariani Avenue, M/S 75-2B, Cupertino, CA 95014.*


Thanks to Casey King and Gary Woodcock for reviewing this column. *

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »

Price Scanner via MacPrices.net

Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
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 currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more

Jobs Board

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
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.