Publications: 0 | Followers: 1

CSS 342 - UW Courses Web Server

Publish on Category: Birds 268

CSS 342
DataStructures, Algorithms, and Discrete Mathematics ILecture 2. 150107.CarranoCH1, C++ Interlude 1
Announcements
Syllabus/Website ReviewCorrection: VS 2013 Update 4HW1 QuestionsCan I get away with a single constructor?Where should I placeconstdefinitions?What do I need to turn in?1/12, Monday: 15min in class peer design review.
Why C++ Object Oriented Programming (OOP)?
AbstractionEncapsulationHierarchyPolymorphism
Encapsulation
Encapsulation and Information Hiding
Wall: Not only encapsulate the entire implementation but also make it invisible/inaccessible.Slit:Interface of the implementation such as arguments and a return value.
Implementationof method S
Programthat usesmethod S
Function call with arguments
Return a value
Class
Classes: a new data type formed of a collection of data and a set of operations on the dataData Structures: a construct within a programming language that stores a collection of data
add
remove
query
Behave as a new data type
Programthat usesa class
Examples:student listsrational numberscomplex numberscurrency (cents/dollars)length measurement (inches/feet)weight measurement (oz/lbs)
Encapsulation at ground level
Program consists ofDriver file (main)Classes (ex,MyClass)MyClass.h-- interfaceMyClass.cpp -- implementationInterface (.h file)public: functions called by othersprivate: data, helper functionsImplementation (.cppfile)MyClass::function()
Examples of private – flush out deck example
constintCARDS_IN_DECK = 52;class Deck{public:Deck();CardDealSingleCard();HandDealHand(intnumber);….interface as defined lasttime….~Deck();private:Card deck[52];};
enumSuit { Diamond, Spade, Heart, Club};class Card{public:Card();Card(intvalue, Suit suit);~Card();private:intvalue;Suitsuit;};
Friends
Declared on either functions or classes; identified with the friend keywordNon-member functions can access private data of an object if it has been declared a friendclass foo{friend classTheClassToGrantAccess;public:private:}
Constructor
Uses same name as class is constructsNothing returned; not even voidDefault constructor createdFunction executed on creation of objectArrays: constructors called in increasing orderArr[0],Arr[1],Arr[2],…Signature chooses constructorCasting of call parameters done using normal casting rulesWhat’s in a constructor?Normally used initialize private data as built-in types in C++ are undefined (inta; a is unknown state)Generally side-effecting is not done
Computer Scientist of the week
EdsgerDijsktra
Shortest Path Algorithm (Dijkstra’sAlgorithm)Semaphores for coordinating multiple processors/programsPioneer in Distributed Systems1972 Turing Award winner (programming languages)Formal verification of programsSchlumberger CentennialChair, University of Texas
C++ Fundamentalslet’s code…
C++ Program Dev Lifecycle
http://www.technovisitors.com/2014/06/C-program-execution-life-cycle.html
IO: Console
#include <iostream>using namespacestd;{intage;cout<< "hello world. How old are you (in years)?\n";cin>> age;cout<< "that is " << (365 * age) << " days.";}
string
http://www.cprogramming.com/tutorial/string.htmlMutable; Copied not shared.stringfirstName= "jimmy";stringlastName("hoffa");stringfullName;fullName=firstName+ " " +lastName;cout<<fullName<<endl;cout<< "First and last letters are:" <<fullName[0] << " " <<fullName[fullName.length() - 1] <<endl;if (fullName== "jimmyhoffa"){cout<< "Found !!!! ";}else{cout<< "oh where oh wherehaveyou gone";}
Callby Value, Reference, and ConstantReference
typedefstruct{intx;inty;} Coordinates;main(){intresult;Coordinatescoord1 = { 3, 3};result= Area(coord1);cout<< coord1.x << " * " << coord1.y << " = " <<result;}
intArea(Coordinatescoord)intArea(Coordinates&coord)intArea(constCoordinates &coord){inttemp;temp=coord.x;coord.x= 35; //Modify to show pass byval, ref,constref semanticsreturn(temp *coord.y);}
Call by Value, Reference, and Constant Reference
Which of swap functions is appropriate?
void swap(string a, string b){stringtmp= a;a = b;b =tmp;}
void swap(const string &a, const string &b){string tmp = a;a = b;b = tmp;}
void swap(string &a, string &b){string tmp = a;a = b;b = tmp;}
Example program: Rational Class
Create a class to represent a rational number
Example program: Rational Class
Create a class to represent a rational numberThis should allow formultiplication, division, addition, subtraction.Comparison (eg, equals)Printing out
First w/o Operator Overloading.PartialRational.h
class Rational{public:Rational();Rational(inta,intb);intgetNumerator()const;intgetDenominator()const;RationalMultiply(Rational rat)const;…. Fill in Divide, Add, Subtract, equals…voidPrintRational(std::ostream&outstream)const;~Rational();private:intnumerator;intdenominator;voidReduce();};
First w/o Operator Overloading.Partial Rational.cpp
void Rational::Reduce(){intgcd= 1;for(inti= 2;i<= min(numerator, denominator);i++){if(((numerator %i) == 0) && ((denominator %i) == 0)){gcd=i;}}if(gcd> 1){numerator/=gcd;denominator/=gcd;}}
First w/o Operator Overloading.Partial Rational.cpp
Rational::Rational(){numerator= 0;denominator= 1;}Rational::Rational(intn,intd){numerator= n;denominator= d;Reduce();}intRational::getDenominator()const{returndenominator;}
Rational Rational::Multiply(Rational rat)const{RationaltempRat;tempRat.numerator= numerator *rat.numerator;tempRat.denominator= denominator *rat.denominator;tempRat.Reduce();returntempRat;}void Rational::PrintRational(ostream&outstream)const{outstream<< numerator << " / " << denominator <<endl;}
BELL RANG
Operator Overload
Allowing for operators to work on classes in intuitive ways.Today we will coverAssignment: =Arithmetic: +, -, *, /Comparison: ==, !=, <, >, <=, >=Input: <<, >>General rules for overloadingWhenever the meaning of an operator is not obviously clear and undisputed, it should not be overloadedAlways stick to the operator’s well-known semanticsAlways provide all out of a set of relatedoperationsOperators retain their precedence order
Overloading +,-,*,/ as member functions
classRational{public:Rational();Rational(inta,intb);intgetNumerator()const;intgetDenominator()const;Rationaloperator*(constRational &rat)const;Rationaloperator/(constRational &rat)const;Rationaloperator+(constRational &rat)const;Rationaloperator-(constRational &rat)const;……….}
Overloading input/output <<, >>
classRational{friendstd::ostream& operator&lt;<(std::ostream&outStream,constRational &rat);friendstd::istream& operator&gt;>(std::istream&inStream, Rational &rat);public:Rational();Rational(inta,intb);intgetNumerator()const;intgetDenominator()const;Rationaloperator*(constRational &rat)const;Rationaloperator/(constRational &rat)const;Rationaloperator+(constRational &rat)const;Rationaloperator-(constRational &rat)const;……….}
More C++ Fundamentals
Pointers
Pointer variablesint*p, *q;Static allocationintx;Address-of operator p = &x;Memory cell to which P points *p = 6;Pointer operations q = p;
?
?
?
p
q
x
?
?
p
q
x
?
6
p
q
x
6
p
q
x
1
3
4
5

0

Embed

Share

Upload

Make amazing presentation for free
CSS 342 - UW Courses Web Server