Transcription of Object-Oriented Programming With ANSI-C
1 V_____PrefaceNo Programming technique solves all Programming language produces only correct programmer should start each project from Programming is the current cure-all although it has beenaround for much more then ten years. At the core, there is little more to it thenfinally applying the good Programming principles which we have been taught formore then twenty years. C++ (Eiffel, Oberon-2, Smalltalk .. take your pick) is theNew language because it is Object-Oriented although you need not use it thatway if you do not want to (or know how to), and it turns out that you can do just aswell with plainANSI-C. Only object -orientation permits code reuse between pro-jects although the idea of subroutines is as old as computers and good program-mers always carried their toolkits and libraries with book is not going to praise Object-Oriented Programming or condemn theOld Way.
2 We are simply going to useANSI-C to discover how Object-Oriented pro-gramming is done, what its techniques are, why they help us solve bigger prob-lems, and how we harness generality and program to catch mistakes earlier. Alongthe way we encounter all the jargon classes, inheritance, instances, linkage,methods, objects, polymorphisms, and more but we take it out of the realm ofmagic and see how it translates into the things we have known and done all had fun discovering thatANSI-C is a full-scale Object-Oriented language . Toshare this fun you need to be reasonably fluent inANSI-C to begin with feelingcomfortable with structures, pointers, prototypes, and function pointers is a through the book you will encounter all the newspeak according toOrwell and Webster a language designed to diminish the range of thought andI will try to demonstrate how it merely combines all the good Programming princi-ples that you always wanted to employ into a coherent approach.
3 As a result, youmay well become a more proficientANSI-C first six chapters develop the foundations of Object-Oriented programmingwithANSI-C. We start with a careful information hiding technique for abstract datatypes, add generic functions based on dynamic linkage and inherit code by judiciouslengthening of structures. Finally, we put it all together in a class hierarchy thatmakes code much easier to takes discipline. Good Programming takes a lot of discipline, alarge number of principles, and standard, defensive ways of doing things right. Pro-grammers use tools. Good programmers make tools to dispose of routine tasksonce and for all. Object-Oriented Programming withANSI-C requires a fair amountof immutable code names may change but not the structures. Therefore, inchapter seven we build a small preprocessor to create the boilerplate required.
4 Itlooks like yet another new Object-Oriented dialect language (yanoodlperhaps?) butit should not be viewed as such it gets the dull parts out of the way and lets usconcentrate on the creative aspects of problem solving with better (sorry) is pliable: we have made it, we understand it and can change it, and itwrites theANSI-C code just like we following chapters refine our technology. In chapter eight we add dynamictype checking to catch our mistakes earlier on. In chapter nine we arrange forautomatic initialization to prevent another class of bugs. Chapter ten introducesdelegates and shows how classes and callback functions cooperate to simplify, forexample, the constant chore of producing standard main programs. More chaptersare concerned with plugging memory leaks by using class methods, storing andloading structured data with a coherent strategy, and disciplined error recoverythrough a system of nested exception , in the last chapter we leave the confines ofANSI-C and implement theobligatory mouse-operated calculator, first forcursesand then for the X WindowSystem.
5 This example neatly demonstrates how elegantly we can design andimplement using objects and classes, even if we have to cope with the idiosyn-crasies of foreign libraries and class chapter has a summary where I try to give the more cursory reader a run-down on the happenings in the chapter and their importance for future work. Mostchapters suggest some exercises; however, they are not spelled out formally,because I firmly believe that one should experiment on one s own. Because we arebuilding the techniques from scratch, I have refrained from making and using amassive class library, even though some examples could have benefited from it. Ifyou want to understand Object-Oriented Programming , it is more important to firstmaster the techniques and consider your options in code design; dependence onsomebody else s library for your developments should come a bit important part of this book is the enclosed source floppy it has aDOSfilesystem containing a single shell script to create all the sources arranged by is aReadMefile consult it before you saymake.
6 It is also quite instructiveto use a program likediffand trace the evolution of the root classes andoocreportsthrough the later techniques described here grew out of my disenchantment with C++ whenI needed Object-Oriented techniques to implement an interactive programminglanguage and realized that I could not forge a portable implementation in C++. Iturned to what I knew, ANSI-C , and I was perfectly able to do what I had to. I haveshown this to a number of people in courses and workshops and others have usedthe methods to get their jobs done. It would have stopped there as my footnote toa fad, if Brian Kernighan and my publishers, Hans-Joachim Niclas and John Wait,had not encouraged me to publish the notes (and in due course to reinvent it allonce more). My thanks go to them and to all those who helped with and sufferedthrough the evolution of this book.
7 Last not least I thank my family and no, object -orientation will not replace sliced , October 1993 Axel-Tobias Abstract Data Types Information Data Example Implementation Implementation Dynamic Linkage Generic and , Messages, Classes and , Dynamic Linkage, and Implementation Implementation Programming Savvy Arithmetic Main Postfix Inheritance Code Reuse and Superclass Implementation and and Dynamic and Access Implementation It or Has It? Inheritance vs. Multiple Programming Savvy Symbol Screener Implementation Implementation Va Subclass Functions Class Hierarchy A New Metaclass TheoocPreprocessor Enforcing a Coding Example List,Queue, Dynamic Type Checking Defensive Example Static Construction Lists for Delegates Callback Abstract Base An Application Framework Another application Class Methods Plugging Memory An Class Implementing Class Programming Savvy A Classy Persistent Objects Storing and Loading Data An Storing Objects puto().
8 Filling Objects geto().. Loading Objects retrieve().. Attaching Objects Exceptions Disciplined Error Implementation Forwarding Messages The Object-Oriented Design by Implementation A Character-Based Interface A Graphical Interface Programming and Pointers void *.. to Global Jumps Variable Argument Lists Data Types Memory Management Memory Functions TheoocPreprocessor Hints Management Generation Main Program Data TypesInformation Data TypesData types are an integral part of every Programming hasint,doubleandcharto name just a few. Programmers are rarely content with what savailable and a Programming language normally provides facilities to build new datatypes from those that are predefined.
9 A simple approach is to form aggregatessuch as arrays, structures, or unions. Pointers, according to C. A. R. Hoare a stepfrom which we may never recover, permit us to represent and manipulate data ofessentially unlimited exactly is a data type? We can take several points of view. A data typeis a set of values chartypically has 256 distinct values,inthas many more; bothare evenly spaced and behave more or less like the natural numbers or integers again has many more values, but they certainly do notbehave like mathematics real , we can define a data type as a set of values plus operations towork with them. Typically, the values are what a computer can represent, and theoperations more or less reflect the available hardware not do too well in this respect: the set of values may vary between machines,and operations like arithmetic right shift may behave complicated examples do not fare much better.
10 Typically we woulddefine an element of a linear list as a structuretypedef struct node {struct node * next;.. information ..} node;and for the operations we specify function headers likenode * head (node * elt, const node *tail);This approach, however, is quite sloppy. Good Programming principles dictatethat we conceal the representation of a data item and declare only the Abstract Data TypesWe call a data typeabstract, if we do not reveal its representation to the user. At atheoretical level this requires us to specify the properties of the data type bymathematical axioms involving the possible operations. For example, we canremove an element from a queue only as often as we have added one previously,and we retrieve the elements in the same order in which they were Abstract Data Types Information HidingAbstract data types offer great flexibility to the programmer.