CS302 Topic: C versus C+ + Thursday, Sept. 8, 2005
Announcements � Lab 1 due tom orrow , before m idnight � Lab 2 due next Friday, Sept. 16 � UT announcement: � Job Fair: Wednesday, Sept. 14, 10-3: 30 at Thompson-Boling � Employers and majors they are seeking available here: � http: / / career.utk.edu/ students/ events_fall.asp
Movies illustrating why OOP helpful for animations
Now, on to C vs. C+ + � C is a subset of C+ + ⇒ most of your C programs should compile as C+ + � programs � Use different compiler: � C compiler: gcc � C+ + compiler: g+ + � Takes same arguments as gcc (e.g., -o, -c, -g, -I) � For fields, dl-lists, rb-trees, use a different library: � / home/ parker/ courses/ cs302/ objs/ libfdr+ + .a
Primary stylistic difference � C is procedurally-oriented � Data structure passed to procedure, along with data needed to manipulate data structure � E.g., “ stack_push(s,1); ” � In C struct, only data can be declared � C+ + is object-oriented � List name of object first, followed by method called to manipulate the object, and the data needed to manipulate the object � E.g., “ s->Push(1); ” � In C+ + object, both data and operations (usually called “ methods ”) can be declared
Classes instead of Structs C C+ + data bundled into struct data + methods bundled into class � Class usually defined in .h header file � Implementation of methods usually defined in a .cpp file
Example 1: C vsn., Stack Manipulation � Application: push 3 integers on stack, then pop off first 2 and print them � First, define C interface to stacks ( stack.h ): typedef void *Stack; /* Allocate and deallocate a stack. New_stack() calls malloc.*/ extern Stack new_stack(); extern free_stack(Stack); /* Test to see if the stack is empty -- or how many elements it as */ extern int stack_empty(Stack); extern int stack_size(Stack); /* Put something on the stack */ extern stack_push(Stack, Jval); /* Take something off the stack */ extern Jval stack_pop(Stack); /* Look at the top element, but don't take it off */ extern Jval stack_top(Stack);
C vsn., Stack Manipulation (con’t.) #include <stdio.h> #include "c_stack.h" main() { Stack s; int i; s = new_stack(); stack_push(s, new_jval_i(1)); stack_push(s, new_jval_i(2)); stack_push(s, new_jval_i(3)); i = jval_i(stack_pop(s)); printf("First pop: %d\n", i); i = jval_i(stack_pop(s)); printf("Second pop: %d\n", i); free_stack(s); }
Now, C+ + vsn. of Stack Manipulation � C+ + object defining Stack: class Stack { public: “Constructor” method: does initialization; Stack(int size); performs same function as new_stack() in C vsn. ~Stack(); void push(int); int pop(); “Destructor” method: eliminates object; performs bool isEmpty(); int top(); same function as free_stack() in C vsn. protected: class StackNode *top_node; }; Calls constructor method Stack s; s = new Stack;
C+ + vsn., Stack Manipulation (con’t.) #include "stack.h" C++ Dynamic Memory: #include < stdio.h > • new : allocates memory, calls constructor method (passing it main() { arguments) and returns pointer to Stack *s; start of it int i; • delete : calls destructor function, then frees memory s = new Stack; previously allocated using new s->push(new_jval_i(1)); s->push(new_jval_i(2)); s->push(new_jval_i(3)); Old way in C: malloc and free • i = jval_i(s->pop()); printf("First pop: %d\n", i); C++ still supports malloc and free, but better to use new and delete i = jval_i(s->pop()); printf("Second pop: %d\n", i); Don’t mix new and delete with delete s; malloc and free in same program! }
Differences between C and C+ + Pgms. � Functional vs. object-oriented C C+ + stack_push(s, new_jval_i(1)); s->push(new_jval_i(1)); � Memory management C C+ + s = new_stack(); s = new Stack; free_stack(s); delete s; � General C+ + formats: new classname(arguments); delete objectname;
Differences, con’t. � Namespaces (simpler naming in C+ + ) C C+ + stack_push(s, new_jval_i(1)); s->push(new_jval_i(1)); � C+ + does better job of carving up namespace � In C, all functions go into same global namespace � � important to ensure that function names that are likely to be popular (like push, pop, top), are not multiply defined � So, we prefix names with things like “stack_”, “queue_”, … � In C+ + , functions can go to global namespace or the namespace of a class (where they’re called methods) � Functions/ methods in different namespaces do not conflict � Example: � push(x): call to global function � s-> push(x): call to method associated with object s
Example 2: Printwords � Application: Read lines of a file and print out each word on separate line, preceded by line number � Example: � Input file: Chocolate is nice but ice cream is dandy � Output: 1: Chocolate 1: is 2: nice 2: but 2: ice 3: cream 3: is 3: dandy
C version of Printwords #include < stdio.h > #include "fields.h" main(int argc, char **argv) { IS is; int i; if (argc != 2) { fprintf(stderr, "usage: printwords filename\n"); exit(1); } is = new_inputstruct(argv[1]); // right here we should check whether is is null and // report an error if it is but the C++ code handles // this case slightly differently (and in a way that // is irrelevant here) so the check is omitted while(get_line(is) >= 0) { for (i = 0; i < is->NF; i++) { printf("%d: %s\n", is->line, is->fields[i]); } } jettison_inputstruct(is); exit(0); }
C+ + version of Printwords � C+ + version of Fields (partial): class Fields { public: Fields(); // implements new_inputstruct for stdin Fields(const string filename); //implements new_inputstruct for a file ~Fields(); // implements jettison_inputstruct int get_line(); // implements get_line int get_line_number(); // return the current line number int get_NF(); // return the number of fields string get_name(); // return the name of the file string get_current_line(); // returns the current line string get_field(int i); // return the ith field in the current line protected: IS file; string name; };
C+ + version of Printwords, con’t. #include < stdio.h > #include "fields.h" main(int argc, char **argv) { Fields *is; int i; if (argc != 2) { fprintf(stderr, "usage: printwords filename\n"); exit(1); } // get a new Fields object is = new Fields(argv[1]); // print out the words prefixed by a line number while(is->get_line() >= 0) { for (i = 0; i < is->get_NF(); i++) { printf("%d: %s\n",is->get_line_number(), is->get_field(i).c_str()); } } // destroy the Fields object delete is; exit(0); }
Revisited: Differences between C and C+ + Pgms. � Functional vs. object-oriented C C+ + get_line(is) is->get_line() � Memory management C C+ + is = new_inputstruct(argv[1]); is = new Fields(argv[1]); delete is; jettison_inputstruct(is);
Revisited (con’t.): Differences between C and C+ + Pgms. � Variable access C C+ + Direct access to variables “Information hiding”: Must call methods to gain access to variables � Hiding variables hides implementation � � makes easier to change class’s implementation without affecting the programs in which the class is used
Example 3: Rectangle � Application: display and manipulate labeled rectangles on a screen, e.g.: ---------------- | | | Mickey Mouse | | | ---------------- � What types of data should be stored? � position (left, top) � size (width, height) � label � color
What types of operations do we need? � draw: draw should paint a rectangle and its label on the screen. � move(x,y): move should move the rectangle to the desired (x,y) coordinates. � resize(width, height): resize should resize the rectangle to the desired width and height. � setLabel(label): setLabel should set the rectangle's label. � setColor(color): setColor should set the rectangle's color. � containsPt(x,y): containsPt should return true if the rectangle contains the given (x,y) coordinates and false otherwise. This operation allows an application to determine whether the mouse cursor is in the rectangle. � getLeft, getTop, getWidth, getHeight, getLabel, getColor: These operations return the current values of the indicated property.
C vsn. of Header file for Rectangle typedef struct rectangle { int left; int top; int width; int height; char *label; char *color; } *Rectangle; void draw(Rectangle); void move(Rectangle, int x, int y); void resize(Rectangle, int width, int height); void setLabel(Rectangle, char *); void setColor(Rectangle, char *); int containsPt(Rectangle, int x, int y); int getLeft(Rectangle); int getTop(Rectangle); int getWidth(Rectangle); int getHeight(Rectangle); char *getLabel(Rectangle); char *getColor(Rectangle);
Recommend
More recommend