CS302 Topic: C versus C+ + Thursday, Sept. 8, 2005 Announcements - - PowerPoint PPT Presentation

cs302 topic c versus c
SMART_READER_LITE
LIVE PREVIEW

CS302 Topic: C versus C+ + Thursday, Sept. 8, 2005 Announcements - - PowerPoint PPT Presentation

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


slide-1
SLIDE 1

CS302 Topic: C versus C+ +

Thursday, Sept. 8, 2005

slide-2
SLIDE 2

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
slide-3
SLIDE 3

Movies illustrating why OOP helpful for animations

slide-4
SLIDE 4

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
slide-5
SLIDE 5

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

slide-6
SLIDE 6

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

slide-7
SLIDE 7

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);

slide-8
SLIDE 8

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); }

slide-9
SLIDE 9

Now, C+ + vsn. of Stack Manipulation

C+ + object defining Stack:

class Stack { public: Stack(int size); ~Stack(); void push(int); int pop(); bool isEmpty(); int top(); protected: class StackNode *top_node; };

“Constructor” method: does initialization; performs same function as new_stack() in C vsn. “Destructor” method: eliminates object; performs same function as free_stack() in C vsn.

Stack s; s = new Stack;

Calls constructor method

slide-10
SLIDE 10

C+ + vsn., Stack Manipulation (con’t.)

#include "stack.h" #include < stdio.h > main() { Stack *s; int i; s = new Stack; s->push(new_jval_i(1)); s->push(new_jval_i(2)); s->push(new_jval_i(3)); i = jval_i(s->pop()); printf("First pop: %d\n", i); i = jval_i(s->pop()); printf("Second pop: %d\n", i); delete s; }

C++ Dynamic Memory:

  • new: allocates memory, calls

constructor method (passing it arguments) and returns pointer to start of it

  • delete: calls destructor

function, then frees memory previously allocated using new Old way in C:

  • malloc and free

C++ still supports malloc and free, but better to use new and delete Don’t mix new and delete with

malloc and free in same program!

slide-11
SLIDE 11

Differences between C and C+ + Pgms.

  • Functional vs. object-oriented
  • Memory management
  • General C+ + formats:

new classname(arguments); delete objectname;

C C+ +

stack_push(s, new_jval_i(1)); s->push(new_jval_i(1));

C C+ +

s = new_stack(); free_stack(s); s = new Stack; delete s;

slide-12
SLIDE 12

Differences, con’t.

  • Namespaces (simpler naming in C+ + )
  • 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

C C+ +

stack_push(s, new_jval_i(1)); s->push(new_jval_i(1));

slide-13
SLIDE 13

Example 2: Printwords

Application: Read lines of a file and print out each word on separate line, preceded by line number Example:

  • Input file:
  • Output:

Chocolate is nice but ice cream is dandy 1: Chocolate 1: is 2: nice 2: but 2: ice 3: cream 3: is 3: dandy

slide-14
SLIDE 14

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); }

slide-15
SLIDE 15

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; };

slide-16
SLIDE 16

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); }

slide-17
SLIDE 17

Revisited: Differences between C and C+ + Pgms.

Functional vs. object-oriented Memory management

C C+ +

get_line(is) is->get_line()

C C+ +

is = new_inputstruct(argv[1]); jettison_inputstruct(is); is = new Fields(argv[1]); delete is;

slide-18
SLIDE 18

Revisited (con’t.): Differences between C and C+ + Pgms.

Variable access

  • Hiding variables hides implementation
  • makes easier to change class’s implementation without

affecting the programs in which the class is used

C C+ +

Direct access to variables “Information hiding”: Must call methods to gain access to variables

slide-19
SLIDE 19

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
slide-20
SLIDE 20

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

  • peration allows an application to determine whether the

mouse cursor is in the rectangle.

  • getLeft, getTop, getWidth, getHeight, getLabel, getColor: These
  • perations return the current values of the indicated property.
slide-21
SLIDE 21

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);

slide-22
SLIDE 22

C+ + vsn. of Header file for Rectangle

class Rectangle { public: Rectangle(int x, int y, int width, int height, char *label, char *color); ~Rectangle(); void draw(); void move(int x, int y); void resize(int width, int height); void setLabel(char *); void setColor(char *); int containsPt(int x, int y); int getLeft(); int getTop(); int getWidth(); int getHeight(); char *getLabel(); char *getColor(); protected: int left; int top; int width; int height; char *label; char *color; };

slide-23
SLIDE 23

Differences between C and C+ + Pgms.

Location of function definitions Function arguments Data accessibility

C C+ +

functions declared outside of struct functions defined inside the class; functions “belong” to the class

C C+ +

functions take rectangle as argument (e.g., draw(Rectangle); no rectangle argument (e.g., draw();)

C C+ +

all variables “public” variables either “public”, “private” or “protected”

slide-24
SLIDE 24

Hit Detection Application

  • Application:
  • Read text file containing info about a collection of

rectangles

  • Read (x,y) coordinate from command line
  • Print out labels of all rectangles that contain that point,
  • rdering rectangles by x or y coordinate (determined by a

–x or –y flag)

  • Input file format:
  • name left top width height color
  • Example:

Kentucky Wildcats 20 80 10 50 blue Tennessee Volunteers 100 200 50 60 orange Ohio State 0 0 20 20 red Florida State Seminoles 60 30 300 200 maroon Lynne Parker 30 30 100 50 red Mickey Mouse 40 60 80 80 black Bugs Bunny 300 10 60 80 gray Daffy Duck 20 20 40 60 white Goofy 60 100 20 20 black

slide-25
SLIDE 25

How would you use the rectangle interface for this application?

class Rectangle { public: Rectangle(int x, int y, int width, int height, char *label, char *color); ~Rectangle(); void draw(); void move(int x, int y); void resize(int width, int height); void setLabel(char *); void setColor(char *); int containsPt(int x, int y); int getLeft(); int getTop(); int getWidth(); int getHeight(); char *getLabel(); char *getColor(); protected: int left; int top; int width; int height; char *label; char *color; }; Mickey Mouse 40 60 80 80 black Bugs Bunny 300 10 60 80 gray Daffy Duck 20 20 40 60 white Goofy 60 100 20 20 black

slide-26
SLIDE 26

General approach

Read input and check for format errors Check for flag (-x, -y) Initialize input structure and red-black tree Read the file, creating rectangles for each line and inserting into tree (keyed on left (x) or top (y) value) – getleft(), getTop() Traverse the tree, printing out all rectangles that contain given point – getleft(), getTop(), getWidth(), getHeight(), containsPt(), getLabel()

slide-27
SLIDE 27

Implementations

We implement a method using this syntax:

return-type classname::method-name(arguments) { ... } int Rectangle::getLeft() { return left; } int Rectangle::getTop() { return top; } int Rectangle::getWidth() { return width; } int Rectangle::getHeight() { return height; } char *Rectangle::getLabel() { return label; } char *Rectangle::getColor() { return color; }

slide-28
SLIDE 28

Implementations, con’t.

void Rectangle::draw() { // code to draw a rectangle on a screen--too complicated to show here } void Rectangle::move(int x, int y) { left = x; top = y; } /* The rectangle always needs to be big enough to accommodate the text label plus have one character of blank space on either side of the

  • label. resize therefore needs to check whether the new width is

less than this threshold amount, and if so, set the width to this threshold amount. Similarly the height needs to be at least 3--one character high for the label, and one character of blankspace above and below the string. In a real interface we would have to compute the pixel height of a character. For simplicity we will assume here that a character has a height of 1. */ void Rectangle::resize(int wd, int ht) { if (wd < (strlen(label) + 2)) width = strlen(label) + 2; else width = wd; if (ht < 3) ht = 3; else height = ht; }

slide-29
SLIDE 29

Implementations, con’t.

/* make a copy of name and store it in the label field. First free the

  • ld label so that we do not have a memory leak. After setting the

label, make sure that the width of the rectangle is enough to accommodate the new label. */ void Rectangle::setLabel(char *name) { free(label); label = strdup(name); if (width < (strlen(label) + 2)) width = strlen(label) + 2; } /* make a copy of the new color and store it in the color field. First free the old color so that we do not have a memory leak. */ void Rectangle::setColor(char *newColor) { free(color); color = strdup(newColor); } /* A rectangle contains a point if the x-value of the point lies between the left and right sides of the rectangle and the y-value

  • f the point lies between the top and bottom of the rectangle */

int Rectangle::containsPt(int x, int y) { return ((left <= x) && (x <= (left + width)) && (top <= y) && (y <= (top + height))); }

slide-30
SLIDE 30

Implementations, con’t.

Rectangle::Rectangle(int l, int t, int w, int h, char *name, char *clr) { left = l; top = t; /* width must be at least equal to the width of name plus one character of blank space on either side of name */ if (w < (strlen(name) + 2)) width = strlen(name) + 2; else width = w; /* height must be at least 3--one character for the label plus one character of blank space above and below the label */ if (h < 3) height = 3; else height = h; label = strdup(name); color = strdup(clr); } Rectangle::~Rectangle() { free(label); free(color); }

slide-31
SLIDE 31

Questions???