DOC PREVIEW
UW CSE 303 - Lecture Notes

This preview shows page 1-2-15-16-17-32-33 out of 33 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 33 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 33 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 33 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 33 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 33 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 33 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 33 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 33 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Slide 1The planReferencesReferences vs. pointersReference parametersconst and referencesStringsString methodsString concatenationLibrariesArraysmalloc vs. newExceptionsMore about exceptionsC++ classesA class's .h fileA class's .cpp fileSimple exampleMore about constructorsMultiple constructorsConstructing objectsA client programClient with pointersStack vs. heap objectsWhy doesn't this code change p1?Object copyingObjects as parametersReferences to objectsconst object referencesconst methodsconst and pointersPointer, reference, etc.?Questions?David Notkin  Autumn 2009  CSE303 Lecture 25The plan11/30 C++ intro 12/2 C++ intro 12/412/7 12/9 12/11Final prep, evaluations12/15FinalCSE303 Au09 2•HW7 is out; new PM due date•Finish last lectureReferences•type& name = variable;•reference: A variable that is a direct alias for another variable.–any changes made to the reference will affect the original–like pointers, but more constrained and simpler syntax–an effort to "fix" many problems with C's implementation of pointers•Example:int x = 3;int& r = x; // now use r just like any intr++; // r == 4, x == 4•value on right side of = must be a variable, not an expression/castReferences vs. pointers•don't use * and & to reference / dereference (just & at assignment)•cannot refer directly to a reference; just refers to what it refers to•a reference must be initialized at declaration–int& r; // error•a reference cannot be reassigned to refer to something elseint x = 3, y = 5;int& r = x;r = y; // sets x == 5, r == 5•a reference cannot be null, and can only be "invalid" if it refers to an object/memory that has gone out of scope or was freedReference parametersreturntype name(type& name, ...) { ...}•client passes parameter using normal syntax•if function changes parameter's value, client variable will change•you almost never want to return a reference–except in certain cases in OOPconst and references•const: Constant, cannot be changed.–used much, much more in C++ than in C–can have many meanings (const pointer to a const int?)void printSquare(const int& i){ i = i * i; // error cout << i << endl;}int main() { int i = 5; printSquare(i);}Strings•#include <string>•C++ actually has a class for strings–much like Java strings, but mutable (can be changed)–not the same as a "literal" or a char*, but can be implicitly convertedstring str1 = "Hello"; // impl. conv.•Concatenating and operatorsstring str3 = str1 + str2;if (str1 == str2) { // compares charactersif (str1 < str3) { // compares by ABC orderchar c = str3[0]; // first characterString methodsstring s = "Goodbye world!";s.insert(7, " cruel"); // "Goodbye cruel world!"method description append(str) append another string to end of this one c_str()return a const char* for a C++ string clear() removes all characters compare(str)like Java's compareTo find(str [, index]) rfind(str [, index])search for index of a substring insert(index, str) add characters to this string at given index length() number of characters in string push_back(ch) adds a character to end of this string replace(index, len, str) replace given range with new text substr(start [, len]) substring from given start indexString concatenation•a string can do + concatenation with a string or char*,but not with an int or other type:string s1 = "hello";string s2 = "there";s1 = s1 + " " + s2; // oks1 = s1 + 42; // error•to build a string out of many values, use a stringstream–works like an ostream (cout) but outputs data into a string–call .str() on stringstream once done to extract it as a string#include <sstream>stringstream stream;stream << s1 << " " << s2 << 42;s1 = stream.str(); // okLibraries#include <cmath>library description cassertassertion functions for testing (assert) cctypechar type functions (isalpha, tolower) cmathmath functions (sqrt, abs, log, cos) cstdiostandard I/O library (fopen, rename, printf) cstdlibstandard functions (rand, exit, malloc) cstringchar* functions (strcpy, strlen)(not the same as <string>, the string class) ctimetime functions (clock, time)Arrays•stack-allocated (same as C):type name[size];•heap-allocated:type* name = new type[size];–C++ uses new and delete keywords to allocate/free memory–arrays are still very dumb (don't know size, etc.)int* nums = new int[10];for (int i = 0; i < 10; i++) { nums[i] = i * i;}...delete[] nums;malloc vs. newmall oc newplace in language a function an operator (and a keyword)how often used in C often never (not in language)how often used in C++ rarely frequentlyallocates memory for anything arrays, structs, and objectsreturns whatvoid* (requires cast)appropriate type (no cast)when out of memoryreturns NULLthrows an exceptiondeallocatingfree delete (or delete[])Exceptions•exception: An error represented as an object or variable.–C handles errors by returning error codes–C++ can also represent errors as exceptions that are thrown / caught•throwing an exception with throw:double sqrt(double n) { if (n < 0) { throw n; // kaboom } ...•can throw anything (a string, int, etc.)•can make an exception class if you want to throw lots of info:#include <exception>More about exceptions•catching an exception with try/catch:try { double root = sqrt(x);} catch (double d) { cout << d << " can't be squirted!" << endl;}•throw keyword indicates what exception(s) a method may throw–void f() throw(); // none–void f() throw(int); // may throw ints•predefined exceptions (from std::exception): bad_alloc, bad_cast, ios_base::failure, ...C++ classes•class declaration syntax (in .h file):class name { private: members; public: members;};•class member definition syntax (in .cpp file):returntype classname::methodname(parameters) { statements;}•unlike in Java, any .cpp or .h file can declare or define any class (although the convention is still to put the Foo class in Foo.h/cpp)A class's .h file#ifndef _POINT_H#define _POINT_Hclass Point { private: int x; int y; // fields public: Point(int x, int y); // constructor int getX(); // methods int getY(); double distance(Point& p); void setLocation(int x, int y);};#endifA class's .cpp file#include "Point.h" // this is Point.cppPoint::Point(int x, int y) { // constructor this->x = x;


View Full Document

UW CSE 303 - Lecture Notes

Documents in this Course
Profiling

Profiling

11 pages

Profiling

Profiling

22 pages

Profiling

Profiling

11 pages

Testing

Testing

12 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?