CS110_08c_OOprograms - EECS110: 8c Object Oriented...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: EECS110: 8c Object Oriented Programming + Misc. Lost Details Jack Tumblin jet@cs.northwestern.edu . Question from TA (2007) Infinite loops: what happens if you do this? eventually? int main() { int i; for(i = 0; i > -1; i++) { // do something useful... } return 0; } Variable i keeps growing; Infinite loops: the set of integers isn't infinite: 31 only holds numbers from -231 what happens if you do this? eventually?to +2 . int main() { int i; when i reaches +231, then i++ will produce i == -231, AND THEN THE LOOP STOPS! Question from TA (2007) for(i = 0; i > -1; i++) { // do something useful... } return 0; } `Collections of Objects': (C++) (Will help on last few projects and beyond) A Game uses a bunch of `somethings': Several different classes (robots, trees, clouds, castles, dogs, cats,...) Each with different actions & abilities: blink(), armsUp(), armsDown(), sleep(), walk(), run(), May want to create/destroy objects as game progresses How can we do that? first ask: How can we store them? Hint: think about a `changing collection of objects' as a `changing collection of struct variables'. `Collections of Objects' (Will help on last few projects and beyond) Idea 0: Declare sets of individually named struct variables for every possible object your program will ever need: fishT carT lokT oneFish, twoFish, redFish, blueFish; carGo, carPet, carToon, carTell; lokNess, awuzLok, shewuzLok, swanLok; All have complete `member' variables that describe absolutely everything that can change: 'name', 'isAlive', 'age', 'position', 'isHungry', isDry', 'energy'... Idea 1: Fixed Arrays of struct variables: an array of fishT objects, an array of carT, an array of lokT. Tedious, inflexible, fixed; can't easily create, destroy, swap, rearrange... Idea 2: Dynamically-Alloc'd Arrays of struct variables; make a pointer-to-fishT, a pointer-to-carT, a pointer-to-lokT, then reserve memory for the array... `Collections of Objects' (useful, but not required in PAs) Idea 3: Make a new struct to point to any ONE thing: (optional; not needed for Project PA-6,7) typedef struct holderT { int kindOf; // if fishT *pF; // if carT *pC; // if lokT *pL; // if } holderT; kindOf==0, kindOf==1, kindOf==2, kindOf==3, we are EMPTY point to a fishT point to a carT point to a lokT The 'kindOf' member variable tells you which pointer (pF, pC, pL, or none) to use. none All the other pointers are kept NULL. typedef struct holderT { int kindOf; // if fishT *pF; // if carT *pC; // if lokT *pL; // if } holderT; `Collections of Objects' kind==0, we are EMPTY! kind==1, points to a fishT kind==2, points to a carT kind==3, points to a lokT Idea 3: (cont'd): Create an object? set the value for kindOf, then malloc()an object for the selected pointer: holderT myn; ... myn.kindOf = 2; // We will hold a carT object myn.pC = (carT *)malloc(1 * sizeof(carT)); myn.pF = NULL; myn.pL = NULL; Destroy an object? use kindof to find its pointer; call free() ... Access an object? Lets try it.... assume a 'carT' object. carT Write code to print its floating-point member 'x_vel' ... x_vel Data Nesting Many forms of data are naturally nested: USE THIS! Universe SolarSystem planet continent country state/ province town precinct street building room chair Matrix row element Movie frame scanline pixel color Least restrictive, cleanest data nesting tool: Structures Nested Structures: members are other structure types allows separate struct name for each nesting level: cityT( street,road,hiway members) streetT(house,building members), houseT(yard,room,hall members), roomT(door,window,furnit. members) furnitureT(desk,chair,bed members), deskT(drawer,leg,top,side...) Wonderful: Structures can use arrays as members (fixed or dynamic alloc'd) `Collections of Objects': (C++) (Will help on last few projects and beyond) We humans tend to organize our world as collections of `objects': 1. We give names to classes of objects: objects (or kinds of objects) birds, clouds, trees, people, triangles, books, animals, buildings, chairs, tables, etc. Each kind of object has many variable parts; parts name, address, salary, dept#, office#, SS#, supervisor, etc. An `object' is one named, countable, discrete entity or idea: idea "Bob Cratchit", emp1, newest_hire, etc. Each class of object has many associated actions: hire, fire, demote, promote, retire, re-assign, work overtime, travel, vacation, training, move to new city, ... 2. 3. 4. `Collections of Objects': (C++) (Will help on last few projects and beyond) Our best strategy in C: Organize the entire program as a collection of `objects'; 1. A `class of object'== data structure type we define and name; and its member variables define each part of the object. 2. 3. 4. One (data-structure-type) variable ==one countable object Each class of object has its own set of related functions wagonInit(), wagonDraw(), wagonMove(), etc. Ideal: all functions are pass-by-reference, just 1 argument, because object contains all the behavior-related attributes. (not always possible: multiple-object interactions, etc.) `Collections of Objects': (C++) The strategy known as "Object-Oriented Programming" (C++, Java, Modula, Smalltalk,...) C++ Java Organize the entire program as a collection of `objects'; 1. A `class of object'== data structure type we define and name its member variables define each part of the object, 2. 3. 4. One (data-structure-type) variable ==one countable object Each class of object has its own set of member functions wagon.Init(), wagon.Draw(), wagon.Move(), etc. In C++, 'class' == ( a struct + its 'member' functions ) `Collections of Objects': (C++) Key idea of object oriented programming: Object = data structure + all its related functions Use nesting of classes to keep things simple: cityT streetT houseT roomT chairT... Writing cityT functions? Please don't make me worry about the number of chairs in each room!. Misc. Lost Details Congratulations! You now know all the essential parts of C ! You're ready for C++, and You're ready to learn a few key algorithms that solve large sets of common problems! There are a few leftover details to clean up first: "Hey! I can even point to myself!" --a data structure Data structure members can be (almost) any type, type including all basic types: int, char, float, double all derived types: enum, arrays, pointers, structures even a pointer to our own kind of struct! if you're careful but we can't hold a fixed array of our own kind of struct (do you know why?) typedef struct employeeT //****employee record ***** { char *name; // string variable int IDnum; // employee ID # float salary; // in dollars char ssn[11]; // xxx-xx-xxxx struct employeeT *pBoss; // immediate supervisor struct employeeT *pPeon;// team member } employeeT; Self-pointing is tricky... Data structure members can be (almost) any type, type including even a pointer to our own kind of struct! SURPRISE! THIS SYNTAX DOESN'T WORK! typedef struct employeeT { char *name; int IDnum; float salary; char ssn[11]; employeeT *pBoss; employeeT *pPeon; } employeeT; //*****employee record ***** // // // // // // string constant employee ID # in dollars xxx-xx-xxxx immediate supervisor team member Self-pointing is tricky... Instead, you must do this: //****employee record**** // // // // // // string constant employee ID # in dollars xxx-xx-xxxx immediate supervisor team member typedef struct employeeT { char *name; int IDnum; float salary; char ssn[11]; struct employeeT *pBoss; struct employeeT *pPeon; } employeeT; ?HUNH? WHAT HAPPENED HERE? 1. actual datatype is `struct employeeT', but typedef renames this datatype to `employeeT' 2. These lines are compiled before typedef can do the renaming, so they must use the actual datatype name: struct employeeT scanf(): more of the story... (CHAPTER 11-6 IN BOOK: look at 11-5 too!) int scanf("format string", ptr1, ptr2, ptr3, ...); Format String: Can set max # of chars for each data conversion: Can set separators (besides whitespace): cnt = scanf("%3d, %80s",&my_int, msg); Return value: # of successful conversions (or 1 if nothing at all matches) Destinations are ALL pointers/array names. scanf(): more of the story... (CHAPTER 11-6 IN BOOK: look at 11-5 too!) int scanf("format string", ptr1, ptr2, ptr3, ...); Format String: Can set max # of chars for each data conversion: Can set required separators (besides whitespace): cnt = scanf("%3d, %80s",&my_int, msg); Return value: # of successful conversions (or 1 if nothing at all matches) Destinations are ALL pointers/array names. scanf(): more of the story... (CHAPTER 11-6 IN BOOK: look at 11-5 too!) int scanf("format string", ptr1, ptr2, ptr3, ...); Format String: Can set max # of chars for each data conversion: Can set separators (besides whitespace): cnt = scanf("%3d, %80s",&my_int, msg); Return value: # of successful conversions (or 1 if nothing at all matches) Destinations are ALL pointers/array names. scanf(): more of the story... (CHAPTER 11-6 IN BOOK: look at 11-5 too!) int scanf("format string", ptr1, ptr2, ptr3, ...); Format String: Can set max # of chars for each data conversion: Can set separators (besides whitespace): cnt = scanf("%3i, %80s",&my_int, msg); Return value: # of successful conversions (or 1 if nothing at all matches) Destinations are ALL pointers / array names. scanf(): more of the story... (CHAPTER 11-6 IN BOOK: look at 11-5 too!!) int scanf("format string", ptr1, ptr2, ptr3, ...); Format String: Can set max # of chars for each data conversion: Can set separators (besides whitespace): To read an entire line (up to 80 chars) of text as a string, replace %80s with %80[^\n]s cnt = scanf("%3i, %80[^\n]s",&my_int, msg); "read a string, but don't stop until you read 80 chars or find a `\n' " Format Strings: Can be a Variable! So far, 1st argument used string constants: scanf(" %d",&val); printf("Value is %d\n",val); But we can use string variables too: (recall: 'string' variable: use a pointer or array name) char inMsg[10] = {" %d"}; char outMsg[20] = {"Value is %d\n"}; ... scanf(inMsg,&val); printf(outMsg,val); (Recall) Literals Numerical literals in C are obvious: int i; double base_e; i = 3; base_e = 2.718281828; OR, more compactly: int i = 3; double base_e = 2.718281828; These literals set the values for i, base_e, and are not L-values--they do not have an address. pV = &3; pF = &2.71828; 3 = &pF; ERROR!! String Literals? String Literals in C are a little strange: they ARE L-values, they DO have address: char *pMsg; String ... pMsg = "Are we having fun yet?"; literal OR, more compactly: char *pMsg = "Are we having fun yet?"; Pointer pMsg gets the address of a string literal. Literal's chars are in 'locked' memory--`const'. ERROR if you try to change its contents! strcpy("Real Soon now!",pMsg); ERROR!! String Constants Reminder: Arrays aren't movable! We can move a pointer pMsg to a string literal's address: address char *pMsg; pMsg = "Are we having fun yet?"; // OK! And we can initialize an array msg by copying a string literal: all chars char msg[20] = {"Are we having fun yet?"}; // OK! But we can't move an array name msg to that location: char msg[20]; msg = "Not this way, no!"; // ERROR! Build a String: sprintf() int sprintf( pStr, format_string, arg0, arg1, ...) Think "string printf" it constructs a formatted, printable string of chars in memory, starting at location pStr. Arguments: pStr char. pointer to showing where to write string format_string (same as used in printf) arg0, arg1, ... list of values used in format string Return value: number of non-null chars written to pStr WARNING!! Reserve a block of memory at pStr first! More about string.h Uses Char Pointer arguments and return types: (pass-by-reference) YOU must ensure enough memory was reserved for all operations of all string.h functions! MAJOR source of subtle bugs! All have form str(n)xxx (dest, src, n), and include: n) copy strcpy, length strlen, compare strcmp, concatenate strcat, find char strchr, find string strstr. Other, more obscure string.h functions: strerror(), strpbrk(), strtok(), strcspn(), strspn(), ... Jargon: Buffer Buffer: temporary storage for data A pointer is NOT a buffer. But it can point to one; Reserved by dynamic allocation (malloc,free) or malloc,free Reserved by a declared array (still in scope, or static) CAUTION: never `over-run' a buffer; make sure all string lengths <= buffer length HELPFUL: All string.h functions have an `n' version: strncpy, strncmp, strncat, strnchr ... operates on only the first `n' characters Subtlety of strncpy, strncat char *strncpy(char* dest, char* src, int n); Always copies `n' chars to `dest'. Of these, it... dest Copies `src' chars until null `\0' char found, then src Copies additional `null' chars after that. null CAREFUL! If `src' longer than n, NO `null' chars!! src null RESULT IS NOT A STRING! char *strncat(char* dest, char* src, int n); Appends no more than `n' chars from src onto dest CAREFUL! If `src' longer than `n', NO null char!! src RESULT IS NOT A STRING! Other useful string.h functions int strncmp(char* str1, char* str2, int n); Compares first `n' characters of strings 1 & 2; Returns the DIFFERENCES; 0 == perfect match! char* strchr(char* str, char ch); Searches string `str' for the 1st char `ch' it finds, Returns pointer to the char it found, or NULL char* strstr(char* str, char ch); Searches string `str1' for the 1st string `str2' it finds, Returns pointer to the string it found, or NULL. Finish up: Worthwhile topics: Search, Sort Chapters Chap 14: Linked lists Intro to C++ Skipped so far: Binary files, String construction sscanf(), printf(). Chap 15: Bitwise operators, bit-shift Appendix G: pre-processor directives: beyond #include Appendix I: command-line arguments. Mostly Archaic Appendix J: Function pointers. Ugly, dangerous, rare. ...
View Full Document

This note was uploaded on 10/05/2011 for the course COMPUTER S 110-1 taught by Professor Tumblin during the Spring '11 term at Northwestern.

Ask a homework question - tutors are online