Summer 91 - USING C++ OBJECTS IN A WORLD OF EXCEPTIONS
USING C++ OBJECTS IN A WORLD OF EXCEPTIONS
MICHAEL C. GREENSPON
The ability to derive C++ objects from MacApp's PascalObject classes yields a
powerful marriage, but not without some misunderstandings between the two
languages. One potentially thorny area crops up in combining exception handling with
dynamic object construction for C++ objects. Judicious use of exception handling
techniques can simplify the development and maintenance of robust, well-structured
applications. But beware: it's easy to get stuck by the undesired interactions of C++
features and wind up in some tangled brush indeed.
Whereas the C++ language supports dynamic storage management implicitly through
object constructors and destructors, Object Pascal relies on user-defined conventions
such as those provided by TObject and adhered to explicitly by MacAppĀ®. In addition,
MacApp defines conventions for exception handling during object initialization. Here
we explore techniques for incorporating MacApp-style exception handling in C++
objects and strategies for object construction, destruction, and dynamic storage
management that provide MacApp compatibility. The challenge is to retain the power of
C++ features while avoiding some potential pitfalls.
First we examine some basic differences in C++ and Object Pascal semantics and
provide an introduction to C++ objects. Then we review the object construction
mechanism used by MacApp and by C++, and present techniques for implementing
MacApp-compatible exception handling in C++. We also present techniques for using
C++ constructors and destructors with PascalObject- derived classes. Finally we
explore some special difficulties and workarounds for using C++ member objects in
handle-based classes.
NOT ALL OBJECTS ARE CREATED EQUAL
Both C++ and Object Pascal rightfully claim to be "object-oriented" languages; yet, in
fact, there are some fundamental differences in expressiveness and meaning between
seemingly similar constructs in the two languages. These differences can be seen by
comparing the object creation process in the two languages:
{ Object Pascal: }
Var obj: TObj;
Begin
New(obj); { Allocate heap storage for a TObj instance }
End;
// C++:
TObj* obj = new TObj; // Allocate and construct a TObj instance on
// the heap
PASCAL NEW STATEMENT ALLOCATES STORAGE
The Pascal New statement allocates relocatable storage on the heap and places a
reference to the storage in the declared object reference variable. In the MacApp
environment, all Pascal objects are allocated as relocatable heap blocks using