DOC PREVIEW
UW CSE 303 - Study Notes

This preview shows page 1-2 out of 6 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 6 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 6 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 6 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

12/2/20091David Notkin  Autumn 2009  CSE303 Lecture 25The plan11/30 C++ intro12/2 C++ intro12/412/712/912/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; // errorcout << i << endl;}int main() {int i = 5;printSquare(i);}12/2/20092Strings• #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 descriptionappend(str)append another string to end of this onec_str()return a const char* for a C++ stringclear()removes all characterscompare(str)like Java's compareTofind(str [, index])rfind(str [, index])search for index of a substringinsert(index, str)add characters to this string at given indexlength()number of characters in stringpush_back(ch)adds a character to end of this stringreplace(index, len, str)replace given range with new textsubstr(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 descriptioncassertassertion 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. newmalloc 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 what void*(requires cast)appropriate type (no cast)when out of memory returns NULL throws an exceptiondeallocatingfreedelete (or delete[])12/2/20093Exceptions• 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; // fieldspublic:Point(int x, int y); // constructorint getX(); // methodsint 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) { // constructorthis->x = x;this->y = y;}int Point::getX() {return x;}int Point::getY() {return y;}void Point::setLocation(int x, int y) {this->x = x;this->y = y;}Simple example• A Point constructor with no x or y parameter; if no x or y value is passed, the point is constructed at (0, 0).• A translate method that shifts the position of a point by a given dx and dy.// Point.hpublic:Point(int x = 0, int y = 0);// Point.cppvoid Point::translate(int dx, int dy) {setLocation(x + dx, y + dy);}12/2/20094More about constructors• initialization list: alternate syntax for storing parameters to fields– supposedly slightly faster for the compilerclass::class(params) :


View Full Document

UW CSE 303 - Study Notes

Documents in this Course
Profiling

Profiling

11 pages

Profiling

Profiling

22 pages

Profiling

Profiling

11 pages

Testing

Testing

12 pages

Load more
Download Study 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 Study 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 Study 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?