290 likes | 579 Views
CS 225 Data Structures & Software Principles. Session 1 Introduction to C++. TA Contact Info. Jeff Naisbitt naisbitt@uiuc.edu Office: 0212 Siebel Center (basement) Office phone: 244-5619 Office Hours (tentative): Tuesday 9-11:00 AM Course URL: http://www.cs.uiuc.edu/class/fa05/cs225.
E N D
CS 225Data Structures & Software Principles Session 1 Introduction to C++
TA Contact Info • Jeff Naisbitt • naisbitt@uiuc.edu • Office: 0212 Siebel Center (basement) • Office phone: 244-5619 • Office Hours (tentative): • Tuesday 9-11:00 AM • Course URL: http://www.cs.uiuc.edu/class/fa05/cs225
Why attend section? • Some topics NOT covered in lectures but are discussed only in section • Get an overview of Jason’s sample code • Review / supplement the regular lecture material • More inviting atmosphere for asking questions • Will try to point out where you might see certain structures/algorithms in future classes, etc.
Main Discussion Topics • Java vs C++ • File Organization & Conventions • Preprocessor • Basic IO in C++ • Java vs C++ class syntax • Code review • The newsgroup • Review Pointers, Memory Ops, Arrays, C-style strings
Similarities Language primitives Control statements Expressions, operators and statement syntax Differences I/O facilities Global variables Libraries Inheritance (differs appreciably) Exception handling Pointers Explicit de-allocation of memory Templates C++ vs. Java
C++ vs. Java (continued) • Advantages of C++ • C++ is generally faster • C++ is more powerful (e.g. pointer arithmetic, templates) • Advantages of Java • Considered “easier” • More portable – especially graphics
C++ File Organization • Header files (*.h) • Holds your declarations and class interfaces • Must be included in all the files referencing the class • #include "file.h" • Source files (*.cpp) • Contain class & function implementations • Driver • int main() • Convention: return 0 on success, non-zero for error
Preprocessor directives • source preprocess compile link exe • #define Constants: #define PI 3.14159265 Macros: #define AREA(radius) PI*(radius)*(radius) • #include • library files (#include <file1.h>) • local files (#include “file2.h”) Need to give the full path • #if, #else, #elif , #endif • #ifdef, #ifndef, #endif • Common convention is to use all capitals • No semi-colon at the end of a directive • Example: When we want to ensure that COORD_H is defined only once #ifndef COORD_H #define COORD_H // class definition #endif
Declarations • Declaring variables of built-in types • int n; (C++ and Java) • Declaring variables of user-defined types • Coord c1; (C++ only) In Java, instance is not created unless new is used. • Allocating objects of built-in types • int* nPtr = new int; (C++ only) • Allocating objects of user-defined types • Coord* cPtr = new Coord(); (C++) • Coord mycoord = new Coord(); (Java)
Jason’s sample code • EWS Machines • /homesta/cs225/src/library/ • MP1 • Understand 01-c++basic/ directory!!
Example:Jason’s error alert functions • Things to Note • Functions • Need not be a part of any class • Declarations in asserts.h • Definitions in asserts.cpp • #ifndef, #define, #endif guards • Including header files with #include
IO in C++ • Streams: an abstraction to I/O devices (e.g. keyboard, mouse, files, array of characters) • iostream: standard I/O library declarations • #include <iostream> • Predefined iostream objects • cin standard input • cout standard output • cerr standard error • Output a newline • endl a function that modifies the output stream (a.k.a. a manipulator)
Standard I/O: Hello World! #include <iostream> using namespace std; int main() { cout << "Hello world" << endl; int a; cin >> a; return 0; }
Namespaces (named scopes) • A way to assign the scope of symbols (functions, objects, etc.) into logical units • Namespace std – contains everything in standard C++ libraries • To import symbols into current namespace • using-directive • using namespace std; • using-declaration • using std::cin; • Using std::cout;
File IO* • Use one of the following classes for file IO • ofstream • ifstream • fstream #include <fstream> using namespace std; int main() { ofstream out("outFile.txt"); if(out) { out << "It's that easy" << endl; } out.close(); return 0; } * don’t need to know for CS 225; see Section 21.5 in Stroustrup
Compiling • > g++ main.cpp clock.cpp • Some compiler flags: • Specify an output name: -o myexe • Add debugging info (still need a debugger!): -g • Compile without linking (*.o): -c • Debugger for Linux/Sun: ddd (graphical front-end for dbx) • Makefiles will make your life easier!
Example:Jason’s alert functions Part 2 • Things to Note • main.cpp • main() and function calling • assert.cpp vs. main.cpp • How things are output using <iostream> • Uses explicit scoping ( std:: ) or not? Why? • Compilation • What gets produced? • How did I produce them?
C++ vs. Java Classes • semi-colon at the end of the declaration • grouping of variable access permissions • classes need not have permissions public, private, etc. • file organization (*.cpp, *.h) • header files need not have the same name as the class • no automatic initialization of variables
Bigger Example:Jason’s courses code • Things to Note • Classes • layout: syntax, grouping, file organization • Constructors • Use of the scope operator in class implementation • Need for include guards • How to create instances • Simple use of cin in main.cpp • File redirection at the command line courseTest < test.1 > myOutput
Code Review:A Debugging Technique • Important aspect of Software Engineering • Can be more efficient than testing • In testing the presence and not the absence of errors is revealed • Problems and not symptoms are detected by reviews, unlike in testing • Compiler error messages may be cryptic • Writing tests is still very useful!
Some Common Errors Syntax Errors? • #include all needed files • #ifndef / #endif in header files • “;” after class • variable spelling • ptr->member vs. object.member • declaring multiple pointers on the same line: each has a * • functions are scoped to classes properly in *.cpp • == vs. =
Some Common Errors Logic Errors? • delete dynamic data? • arrays indexed correctly? • loops iterate correct # of times? • initialize my variables? • Am I trying to dereference NULL? (segfaults) Makefile Errors? • Am I using tabs to indent (and NOT spaces)? • Did it properly recompile the code I modified? • If not, did I create the proper dependencies in the Makefile? • Is it linking all the object code (*.o) together? • Did it link to the code with main() in it?
Sample code (Problem!) #include <iostream> #define PI 3..14159 int main() { cout << “The value of pi is”<< PI << endl; return 0; }
Remember… • Set your AD Password for EWS lab access • http://accounts.ad.uiuc.edu/ • Subscribe to the class newsgroups • See my newsgroups link • Read the Unix & Makefile tutorials
Pointers • Pointer: a variable that holds a memory address • Its datatype depends on type of variable it points to • Initialize • by making it a null pointer (points to address 0) • int* i = NULL; • or point to a valid memory address • Dangers • Dangling pointers • Memory leaks • Accessing invalid memory
Memory Operators • Address-of (&) int* a = &myInt; • De-reference/”Value-of” (*) cout << *a; • Allocate (new) Obj* ptr = new myObj(); • De-allocate (delete) delete ptr; • Member selection ( -> or . ) Obj* ptr = &myObj; ptr->memberFn(); // (*ptr).memberFn(); // equivalent to prev. line myObj.memberFn();
Pointer Arithmetic & Arrays • Arrays are stored in contiguous memory • iAry[i] *(iAry + i) • Example: int iAry[4]; iAry[2] = 20; cout << "Element 3 is " << *(iAry+2) << endl; outputs: Element 3 is 20 • Name of array can be used as pointer to its initial element • Actual address offset size in bytes is dependent on data type stored
More Arrays • Local (stack): int intArray[10]; int intArray2[] = { 1, 2, 3 }; Obj objArray[4] = { Obj(), Obj(2), Obj(9) }; • Dynamic (heap): int* intArray = new int[10]; delete[] intArray; // delete intArray; Wrong! Undefined… // vs. int* i = new int(); // NOT an array delete i; // delete[] i; Wrong! Undefined… • Default constructor is used when creating an array of objects • Do not step beyond the bounds of your array
Arrays and C-style strings • String literals are of type: const char* cout << "this is a string literal"; • null terminated: '\0' • Examples: • Locally allocate and initialize a modifiable string char str[] = "Data Structures"; • str’s length is 16 characters long! • Un-modifiable string literal const char* str2 = "CS 225"; • Dynamic char* str3 = new char[3]; str3[0] = 'h'; str3[1] = 'i'; str3[2] = '\0';