COMS W3156: Software Engineering, Fall 2001 Lecture #21: C, C++ Janak J Parekh

Slides:



Advertisements
Similar presentations
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Advertisements

Destructors Math 130 Lecture # xx Mo/Da/Yr B Smith: New lecture for 05. Use this for evolving to Java B Smith: New lecture for 05. Use this for evolving.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Software Engineering Nov-01 #21: Language II Phil Gross.
Software Engineering Nov-01 #23: OS, Language, Design Patterns Phil Gross.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
COMS W3156: Software Engineering, Fall 2001 Lecture #20: C, continued Janak J Parekh
COMS W3156: Software Engineering, Fall 2001 Lecture #22: C, C++, OS, etc… Janak J Parekh
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Pointers and Arrays C and Data Structures Baojian Hua
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Review of C++ Programming Part II Sheng-Fang Huang.
Lecture 03a: C++ classes Topics: basic classes and objects constructor, destructor Miscellaney An intro to the STL (Standard Template Library)
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
Moving from C to Java. The Java Syntax We Know Java Types Some of the types we know and love are still there  Integer: byte, short, char, int, long.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Intro to C++ And Some Tools Opening Discussion zHave any questions come up since last class? Have you had a chance to look over the project.
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
By – Tanvir Alam.  This tutorial offers several things.  You’ll see some neat features of the language.  You’ll learn the right things to google. 
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
CS 11 C++ track: lecture 4 Today: More on memory management the stack and the heap inline functions structs vs. classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
Pointers OVERVIEW.
C++ Memory Overview 4 major memory segments Key differences from Java
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
Pointer to an Object Can define a pointer to an object:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
CS212: Object Oriented Analysis and Design
Classes, Constructors, etc., in C++
Overview of C++ Polymorphism
CS410 – Software Engineering Lecture #5: C++ Basics III
LCC 6310 Computation as an Expressive Medium
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

COMS W3156: Software Engineering, Fall 2001 Lecture #21: C, C++ Janak J Parekh

Administrativia “Where’s the prototype???” Wednesday! Moved code review deadline Interested in doing research? –Come see me, or consider the research fair happening next Friday, the 30 th, 10am-4pm – –For the fair, you need to sign up, but free food!

Project update Deformalize (demodalize) chat? –Needed for logging –Formal seems too cumbersome –Software Engineering problem: keep reqs or change them? ChangeOther for bots –How to communicate to server? –Introduce RequestActorChange, or in MapDelta?

Project update (II) Death sequence? –Attacked message, with death boolean set to true –Kick the user from the game –Delete the object from the map –Remove the player from LDAP: HP no longer make sense WrappedOutputStream: need to use for final implementation WebServer: to serve up Images correctly, need Content-Length –I’ve put up my WebServer

Next class Grr, Phil has one more class than we do –You can go attend his class tomorrow if you like: heavy C++ treatment My next class begins operating systems and “design patterns” –I’ll probably go over a bit more C++ –But also recitation next week

Today’s class Finish C Intro to C++

Pointer examples int x = 7; int *ip = &x; printf(“%d\n”, ip); // What does this print? printf(“%d\n”, *ip); *ip = 9; printf(“%d\n”, *ip); printf(“%d\n”, x);

Pointers: miscellany If ip == 4, and ints are 4 bytes long, what does ip+1 equal? –This is why pointers are “typed” C does not have real arrays –Basically consecutive blocks of memory pointed to int a[7]; a == &a[0]; ++a == &a[1]; Nothing, even pointers, are null-initialized

C’s use of pointers C does not have Strings either –Basically an array of chars (char *) Basically a pointer to a block of memory Char pointers are all over the place C’s loose typing: the meaning of “0” –False –End-of-string character –Null pointer (#define NULL 0)

Using pointers void foo(int *i) { *i = 5; } int main(void) { int i = 0; foo(&i); }

Using pointers (II) Note that * and & essentially “cancel each other out” What if we didn’t have anything to point the pointer to, initially? What if we want to allocate memory in general for a pointer/reference without a “static” variable?

This is bad int *foo(void) { int i = 5; return &i; } int main(void) { int *j = foo(); }

Huh? I lied: C has one form of garbage collection –Local variables that are allocated get cleaned up –Well, not really cleaned up: just deallocated Need to manually allocate memory and assign it to a pointer –The malloc() command –Think of it as a poor man’s new()

Much better int *foo(void) { int *i = (int *)malloc(sizeof(int)); *i = 5; return &i; } int main(void) { int *j = foo(); }

Oh dear… Any memory you malloc(), you must then free() –Unless you want to wait till the program ends –You don’t want to –“Save the whales. Free the mallocs.” Otherwise, you’ve got an (insidious) memory leak Again, philosophy is that you do everything

Sidebar: C == evil void foo(char *dst, char *src) { while (*dst++ = *src++); } Yes, this code actually compiles and runs What does it do? * has higher precedence than ++ Strings terminated by a “\0”, or 0 character, which is false Wacky, huh?

Passing multiple values So, in Java, how do you pass multiple values? –Lots of parameters (bad) –Pass a complex Object into a method call, and have it modify the Object –Return a new Object In C? –No objects! –But, there are structs …

Struct Basically, a class without methods struct Point { int x; int y; }; /* note the semicolon */ int main(void) { struct Point myPoint; myPoint.x = 5; myPoint.y = 5; }

Now, how to pass this around? You don’t want to pass it call-by-value –Slow –Can’t return results back all that easy You want to return it via call-by-reference –Pass a pointer to the struct around

Back to foo() struct Point { int x; int y; }; void foo(struct Point *myP) { (*myP).x = 5; (*myP).y = 5; } int main(void) { struct Point myPoint; foo(&myPoint); }

Miscellany on structs (*myP).x looks ugly –C has a bizarre shortcut: myP -> x –Yes, a dash followed by a greater than –Always remember that a -> b is equivalent to (*a).b –Precedence of operators It’s cumbersome to have to say struct Point every time –Use typedefs: define “aliases” –typedef struct Point PointT; –or even typedef struct Point *PointP;

More miscellany on structs Since not everything happens in main, malloc’ing structs is very common –The sizeof operator works on pretty much any datatype, be it structs or primitive datatypes –Guaranteed tip: you will come across PointP myP = (PointP)malloc(sizeof(PointP)); –and be glad that you were attending this class…

Function prototypes As I said, C’s compiler is not all that smart If you have: int main(void) { int i = foo(); } int foo(void) { return 5; } It will not work

Function prototypes (II) Need to clue in the compiler by putting the following prototype before main: int foo(void); Looks like a Java interface construct Often, you collect the prototypes into a header (.h) file, then #include it into your various source (.c) files

On various.c files… A common way to build multi-source-file code in C is to –build a set of.h files that export functionality (i.e. “public” methods) –#include these.h files –Compile and link the.c files together As long as you have a prototype, the compiler will not care about the definition –Like compiling against an Interface –The Linker will, though…

C++ Not strictly a superset of C, but C++ compilers backwards-compatible with C –Certain subtle language differences –C with classes, but a whole lot more Function, operator overloading Powerful “template” functionality (Phil – tomorrow) Exceptions

Quick primer to C++ g++ is the GNU C++ compiler –Actually a C++ plugin to gcc Can feed C code to it, will work fine Can integrate C and C++ code pretty easily However, ideally, you want to avoid using many C constructs

Hello, world in C++ #include using namespace std; int main(void) { cout << “Hello world\n”; } Note use of namespaces, streams << operator is overloaded to allow combination/concatenation of strings with streams Can do cout << “foo” << “bar” << endl;

Class declarations in C++ class Rectangle { private: double width; double height; public: Rectangle(int width, int height); ~Rectangle(); void setWidth(int width); int getArea(); // and so on… }

Implementing methods Inline in the class declaration Or, use the class as a prototype and implement elswhere void Rectangle::setWidth(int w) { width = w; }

Constructors and destructors You have both, not just one Motivation of destructor: cleanup the object, free any memory, etc. Don’t use C++’s default denstructor if you new anything –You should delete anything you new –Don’t use malloc/free unless absolutely necessary

C++ miscellany Operator overloading: nice, but must be careful –Often need to override assignment and copy operators if you have funky data structures (e.g, the “=” operators) References in function prototypes (finally!) Templates: “type” data structures STL: Standard Template Library –You now have “string”s! –Lots of other data structures –Somewhere between C and Java API’s –Very, very fast if used correctly