TweetFollow Us on Twitter

April 91 - Reading C++ Interfaces

Reading C++ Interfaces

Eric M. Berdahl

Many of you have seen the traffic on MacApp.Tech$ discussing the relative merits of C++, Pascal, Eiffel, and whatever else happens to work with MacApp-or will someday. Each of you has chosen one or more languages in which to express your designs and has gone happily forward.

For those using Pascal, everything has been rather simple. Since MacApp is written in Pascal, the compiler takes care of almost everything. The rest of us learned a little about the "magic" that Pascal throws under our feet, and went happily on our way. Everyone was happy.

But every happy story needs a plot twist to make it really interesting. The particular twist that faces us now involves C++, MacApp, and Apple itself. If you haven't heard it yet, listen up: at the MADA conference in February, Apple announced that MacApp 3.0 is being written in C++.

After the bomb dropped, the dust settled, and the damage assessments began, we learned that Pascal wasn't yet dead and buried. However, we all began to realize that knowing a bit of what's out there besides Object Pascal might not be a bad idea.

Come on into the Kitchen!

Welcome to The Soup Kitchen. As with soup left alone too long, our community has settled into various layers with little interlayer interplay. Thus, today's menu features a Pascal layer and a C++ layer, but never the 'twain do meet. As any cook knows, such soups have little taste-so The Soup Kitchen will stir things up a bit, by exploring the uncharted realms of MacApp programming.

The ability to work with C++ is a dish I think you will enjoy-or at least tolerate-once you see a bit about how it works and what goes into the pot. So for my first series of columns, I'll address the needs of the non-C++ community to work with MacApp code written in C++. Since it is widely accepted that one must read MacApp source code sometimes, the first goal will be to give everyone a basic reading knowledge of C++.

Next, to address the large audience that has a need to modify MacApp, I'll show you how to modify C++ code. Finally, some of you will want to catch the wave and change to C++ altogether. This will be my eventual topic also.

Today, let's look at what you might find in C++ interfaces.

Inheritance and Polymorphism

The term "object programming" carries a lot of weight. Depending on who you're talking to, you'll hear about things like garbage collection, stack objects versus free store objects, and exception handling. However, to do "object programming," you need only two things-just inheritance and polymorphism, nothing else. In fact, these are the only two object concepts provided by Apple's Object Pascal language [1] . That is, Object Pascal allows you to write classes which inherit from superclasses and to override methods of superclasses. This is a natural place to begin learning to read C++.

C++ Class Declarations

Listings 1 and 2 contain excerpts from the Nothing sample program provided with MacApp 2.0.1. They are equivalent Pascal and C++ versions of the TNothingApplication object. TNothingApplication is a simple class, but it will show many of the basics of class declarations in C++.
class TNothingApplication : public TApplication {

This line tells us we are beginning the declaration of a class called TNothingApplication which inherits from TApplication. Everything between the { and its matching } is the class declaration. Simple, right? Ok, says the quick reader, but what does that public keyword mean, and what exactly is the significance of the colon? Good questions. The basic form of the class statement is:

class <Name of class> : public <Name of superclass> {
<Instance variables and methods>
};

A colon following the name of the class indicates that the class inherits from something [2] . The public keyword used in this location is a bit more difficult to explain without confusing the novice further than necessary. For now, we'll just say you always want to use it as you see it above.

Keyword-public
class TNothingApplication : public TApplication {
public:

Here's that funny public keyword again, so it's time to explain a bit of the magic of C++. Since one of the tenets of object programming is data hiding, C++ provides a compiler-enforced system for hiding data within objects. Features of the class declaration following public: are visible to everyone. Thus, anyone has access to them and can use them.

In contrast, sections of the class declaration following private: are visible only to methods of the class. Thus, only methods of the class can use private features. No one else, not even a method of a subclass, has access to private features. (Compare this to Object Pascal; it has no such data hiding syntax, at least not until '9x comes around, so everyone has access to everything about the class.) Sections of public: features and sections of private: features can be mixed freely in a class to denote the relevant access of any particular feature.

Let's go back and look at the public keyword in the first line of the class declaration. What the public keyword means here is that all the public features of the superclass should be public for the new class also. If the inheritance was private, the client (something which uses a particular object) would interact with our class only through our features, and not through anything our superclass does. As I said before, you will probably use public inheritance exclusively.

Keyword-protected

Another protection offered by C++ is protected:. Protected features of a class are visible to the class and its immediate subclass. If a class inherits publicly, protected features of the superclass are protected features of the derived class. Inheriting privately makes public features of the superclass private features of the derived class. And, before you ask-no, you can't inherit "protectedly."
Comment syntax and method declaration
class TNothingApplication : public TApplication {
public:
   // Initializes the application and globals. 
   virtual pascal void INothingApplication(
                          OSType itsMainFileType);

The // token is a comment delimiter. Everything between it and the next return character is a comment. The following line is a declaration of a method of TNothingApplication. The method's name is INothingApplication, and it has one argument, itsMainFileType, of type OSType. (Remember that C++ uses the C-style argument declarations, so the type precedes each argument.)

Keyword-virtual

The virtual keyword used in this position indicates that the method will be polymorphic. Since Pascal only knows about polymorphic methods, and our goal is to be usable from and linkable to Pascal, all our methods should be declared virtual [3].

The pascal void construct

The pascal void construct is a little easier to explain. The pascal keyword indicates that the method will use Pascal calling conventions (as opposed to C calling conventions). You probably always want to use this since Pascal cannot emulate other calling conventions. Since every routine in C++ is a function (all routines have the ability to return a value), void is the way of syntactically saying that a function returns nothing. This is equivalent to declaring a PROCEDURE in Pascal. Naturally, if the routine (or method, as the case may be) actually is meant to return something, the return type of the routine would be substituted for void.

Comment your overrides

Unlike Pascal, C++ does not have an OVERRIDE keyword. As a matter of style, many style guides and C++ programmers-myself included-recommend tagging all overrides with a comment like "// OVERRIDE" to indicate that you are overriding the method.
class TNothingApplication : public TApplication {
public:
   // Initializes the application and globals. 
   virtual pascal void INothingApplication(
                          OSType itsMainFileType);
};

With the final } and the semicolon, our class declaration is complete.

Instance variables

Instance variables are the only thing missing from our treatment of class declarations. Listings 3 and 4 show a C++ class that looks just like TNothingApplication with a few instance variables, and its Pascal correlate.
class TNewNothingApplication : public TApplication {
public:
   short    fAnInteger; // Integer instance variable
   long     fLongInt;   // LongInt instance variable
   char     fAChar;     // Char instance variable

protected:
   TObject* fATObject;  // TObject instance variable

   // Initializes the application and globals. 
   virtual pascal void INothingApplication(
                          OSType itsMainFileType);
};

Notice that instance variables are declared using the C-style syntax of putting the type before the variable name. And that the C++ types short, long, and char correspond to the Pascal types Integer, LongInt and Char.

The only real brain stretcher here is the TObject* fATObject declaration. Read literally, this declaration says fATObject is of type pointer to TObject. In Pascal, the compiler takes care of dereferencing, so all objects look just like regular variables-hence the equivalent fATObject: TObject.

In C++, variables which are Pascal objects look like pointers to variables; hence the TObject* syntax. As you'll see later, you manipulate Pascal object variables just like pointers in the same way that Pascal manipulates object variables just like variables.

Notice that TNewNothingApplication uses the private: and protected: access features of C++. In this example, fAnInteger, fLongInt, and fAChar are all private, so only TNewNothingApplication methods will be able to access them. The fATObject instance variable is protected and will only be visible to TNewNothingApplication and its descendants.

It's important to realize that the equivalent Pascal declaration is oblivious to the access restrictions C++ has placed on the class' instance variables and methods. This is because the access restrictions the C++ compiler enforces are syntactic only; they don't have any effect on the object code produced by the compiler. Thus they don't affect our ability to link with Pascal in the slightest.

Declaration of Constants and Types

There are a lot of constants declared in MacApp interfaces. So, how do you declare constants in C++? Persons familiar with standard C code will recognize #define statements as macro definitions and point to these as methods of declaring constant values, but C++ provides a better mechanism-the const facility. It works like this: take any variable declaration (i.e. short kSomeConstant;), put the const keyword in front and give it a value (i.e. const short kSomeConstant = 1;) and you have declared a constant value.

This has several advantages over the C-style #define mechanism and the Pascal CONST declarations. The C++ constant is given an explicit type, whereas the the other language's constants have implicit types assigned by the compiler. In Pascal, the intended type is often obvious to the reader anyway, but the const declaration in C++ allows anything to be a constant-strings, objects, records, you name it.

Finally, it's necessary to define types in terms of other types and to define non-object data structures. The first task is done by typedefs:

TYPE Mask = INTEGER; { Pascal type declaration }
typedef short Mask; // C++ type declaration

These two lines of code define the type Mask to be equivalent to a 16 bit word (i.e. INTEGER in Pascal and short in C++). The second task is handled by struct declarations. Pascal RECORDs and C++ structs look virtually the same. The central difference is the fact that the type precedes the field name.

Rect = RECORD
      top:          INTEGER; 
      left:         INTEGER; 
      bottom:       INTEGER;  
      right:        INTEGER; 
   END;                     
   
struct Rect {
      short         top;
      short         left;
      short         bottom;
      short         right;
};

Looking for Feedback

Now you know the basics of reading C++ interface declarations in MacApp code and understand how to correlate these with Pascal. In the future, we'll cover more of the same and in greater depth.

This column isn't for me, for Apple, or for MADA-it's for you, the reader. I hope you like it. Feedback, questions, and suggestions for future directions and topics are encouraged at my AppleLink address. Who knows, you may end up being the subject of a column! n

Footnotes:

  1. One of my reviewers remarked that I was selling Pascal and other languages short by omitting other "object concepts" such as encapsulation. While such features are certainly part of the object programming tradition, my purpose here is really to separate object programming from other paradigms (e.g. structured programming) which also provide encapsulation yet are not considered object-oriented.
  2. …and if you want to be usable from Pascal code, your C++ classes must always inherit from something. Since Pascal's method dispatching is very different from C++, Apple's implementation of C++ includes the PascalObject class. Classes that inherit from PascalObject will use Pascal style method dispatching and are usable from Object Pascal code. Now, does this worry you? Probably not, since most (if not all) of your classes descend from TObject. Guess what TObject inherits from? PascalObject.
  3. For the technically masochistic: virtual indicates that a method will be polymorphic-it will bind at runtime. If we do not declare a method as virtual, the compiler would perform compile-time binding of the method call based on the static type of the object. Compare this to Pascal, which only allows dynamic binding. The take-home lesson: use virtual if you want your methods to be accessible from Pascal. Likewise, any methods of Pascal objects must be declared virtual so C++ can access them. Generally, you want all your methods to be virtual anyway, right? So, just use it and be happy.
 
AAPL
$101.58
Apple Inc.
+0.72
MSFT
$46.52
Microsoft Corpora
-0.24
GOOG
$584.77
Google Inc.
+4.82

MacTech Search:
Community Search:

Software Updates via MacUpdate

Apple Configurator 1.6 - Configure and d...
Apple Configurator makes it easy for anyone to mass configure and deploy iPhone, iPad, and iPod touch in a school, business, or institution. Three simple workflows let you prepare new iOS devices... Read more
SpamSieve 2.9.16 - Robust spam filter fo...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
OS X Server 3.2.1 - For OS X 10.9.5 Mave...
OS X Server is the next generation of Apple's award winning server software. Designed for OS X and iOS devices, OS X Server makes it easy to share files, schedule meetings, synchronize contacts, host... Read more
Apple Security Update 2014-004 - For OS...
Apple Security Update is recommended for all users and improves the security of Mac OS X. For information on the security content of this update, please visit this website: http://support.apple.com/... Read more
OS X Mavericks 10.9.5 - The latest versi...
Apple OS X Mavericks is the latest release of the world's most advanced desktop operating system. Now free! With more than 200 new features, OS X Mavericks brings Maps and iBooks to the Mac,... Read more
iExplorer 3.5.0.0 - View and transfer al...
iExplorer is an iPhone browser for Mac lets you view the files on your iOS device. By using a drag and drop interface, you can quickly copy files and folders between your Mac and your iPhone or... Read more
BusyCal 2.6 - Powerful calendar app with...
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
Apple iOS 8.0 - The latest version of Ap...
The latest version of iOS can be downloaded through iTunes. Apple iOS 8 comes with big updates to apps you use every day, like Messages and Photos. A whole new way to share content with your family.... Read more
Apple Digital Camera RAW Compatibility 5...
Apple Digital Camera RAW Compatibility update adds RAW image compatibility to Aperture 3 and iPhoto '11. For more information on supported RAW formats, see here.Version 5.07: Adds RAW camera... Read more
Transmit 4.4.7 - Excellent FTP/SFTP clie...
Transmit is an excellent FTP (file transfer protocol), SFTP, S3 (Amazon.com file hosting) and iDisk/WebDAV client that allows you to upload, download, and delete files over the internet. With the... Read more

Latest Forum Discussions

See All

Paste+ | Clipboard Action Widget (Produ...
Paste+ | Clipboard Action Widget 1.0.0 Device: iOS iPhone Category: Productivity Price: $3.99, Version: 1.0.0 (iTunes) Description: Powerful clipboard widget for iOS 8. Reimagine what you can do with your clipboard! Paste+ is a... | Read more »
Agenda+ | Calendar & Reminder Widget...
Agenda+ | Calendar & Reminder Widget 1.0.0 Device: iOS iPhone Category: Productivity Price: $1.99, Version: 1.0.0 (iTunes) Description: Best Calendar and Reminder Widget Ever for iOS 8 | Read more »
Leg·end·ar·y (Games)
Leg·end·ar·y 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Simple and yet complex. Leg•end•dar•y is a grid-based puzzle game based on numbers. Discover the adventure of Leg•end•dar•y and... | Read more »
KuaiBoard (formerly QuickBoard) (Utilit...
KuaiBoard (formerly QuickBoard) 1.0 Device: iOS Universal Category: Utilities Price: $1.99, Version: 1.0 (iTunes) Description: KuaiBoard is currently 50% off for launch! Billing info. Signatures. Locations. KuaiBoard allows you to... | Read more »
Treasure Fetch - Adventure Time (Games)
Treasure Fetch - Adventure Time 1.0.1 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.1 (iTunes) Description: Adventure Time Treasure Fetch is a fresh take on the classic Snake game! STRETCHY JAKE Snake your way... | Read more »
Light in the Dark (Games)
Light in the Dark 1.1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.1.0 (iTunes) Description: Be enlightened by this delightful puzzle game that has never before seen the light of day! "A physics and color-blending... | Read more »
Transmit iOS (Utilities)
Transmit iOS 1.0 Device: iOS Universal Category: Utilities Price: $9.99, Version: 1.0 (iTunes) Description: >> LAUNCH SPECIAL: Transmit iOS is ONLY $10 for a LIMITED TIME. << THE #1 FILE TRANSFER CLIENT FOR THE MAC NOW... | Read more »
Minuum - The Little Keyboard for Big Fin...
Minuum - The Little Keyboard for Big Fingers 1.0 Device: iOS iPhone Category: Utilities Price: $1.99, Version: 1.0 (iTunes) Description: Type faster, see more of your screen, and take control of autocorrect with Minuum: the little... | Read more »
TextExpander 3 + custom keyboard (Utili...
TextExpander 3 + custom keyboard 3.0 Device: iOS Universal Category: Utilities Price: $4.99, Version: 3.0 (iTunes) Description: | Read more »
Swype - Keyboard (Utilities)
Swype - Keyboard 1.0.1411 Device: iOS Universal Category: Utilities Price: $.99, Version: 1.0.1411 (iTunes) Description: Why type when you can Swype? One of the most requested apps for iPhone is finally here. "If Swype itself ever... | Read more »

Price Scanner via MacPrices.net

Toshiba Introduces TransMemory ID High-Speed...
Toshiba’s Digital Products Division (DPD), a division of Toshiba America Information Systems, Inc., today introduced the TransMemory ID USB 3.0 Flash Drive, a simpler storage solution for people who... Read more
New iPads and OS X Yosemite Release Coming Oc...
The DailyDot’s Micah Singleton reports that Apple is planning to hold its next product announcement event on Oct. 21, at which it will unveil the iPad Air 2 and iPad mini 3 and release a final build... Read more
Logitech Bluetooth Multi-Device Cross-Platfor...
Logitech has an enviable track record of making some of the best computer keyboards and mice. At least in my estimation, the best freestanding keyboards I’ve ever used have been Logitech units,... Read more
Roundup of Apple refurbished iPad Airs and iP...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
Sprint offers 16GB iPad mini for $199.99 with...
Sprint is offering 1st generation 16GB iPad minis for $199.99 with a 2-year service agreement. Standard MSRP for this iPad is $429. Their price is the lowest available for this model. Read more
2.5GHz Mac mini remains on sale for $549, sav...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Apple refurbished iMacs available for up to $...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
13″ 2.5GHz MacBook Pro offered for $100 off M...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $999.99 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
Free GIMP Professional Grade Graphics App Ver...
The latest 2.8.14 version of the oddly-named GIMP (acronym for: GNU Image Manipulation Program) open source, high-end image editing and creation alternative to Adobe’s Photoshop and refuge from... Read more
Apple Announces Record Pre-orders for iPhone...
Apple has released metrics showing a record number of first day pre-orders of iPhone 6 and iPhone 6 Plus, with over four million sold in the first 24 hours. Demand for the new iPhones exceeds the... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.