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.
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.