CSS 342 Data Structures, Algorithms, and Discrete Mathematics I

Slides:



Advertisements
Similar presentations
More on Classes. COMP104 ADT / Slide 2 Abstract Data Type * An Abstract Data Type is a class with some special restrictions. * These restrictions can.
Advertisements

Operator Overloading Back to Fractions.... Implementing an Object We’ve talked at length about object- orientation. – We’ve looked heavily at encapsulation.
Class and Objects.
Abstract Data Types Development and Implementation JPC and JWD © 2002 McGraw-Hill, Inc.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Abstract Data Types Development and Implementation.
Abstract Data Type. COMP104 Slide 2 Summary l A class can be used not only to combine data but also to combine data and functions into a single (compound)
Lecture 4 OOP Course. 4. Operators Using constructors: String int main(){ String s1(“My String”); String s2(s1); String s3; s3=s1; } int main(){ String.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 14. User Defined Classes.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R1. ADTs as Classes.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Chapter 6 One-Dimensional Arrays ELEC 206 Computer Tools for Electrical Engineering.
Case Study - Fractions Timothy Budd Oregon State University.
Introduction to Classes in C++
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CH1, C++ INTERLUDE 1.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CH 2, APPENDIX E.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
1 Lecture 17 Operator Overloading. 2 Introduction A number of predefined operators can be applied to the built- in standard types. These operators can.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO , APP D, C++ BOOK.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO C++ INTERLUDE 2, CHAPT 4, 6.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Operator Overloading.
CSE1002 – Problem Solving with Object Oriented Programming
Operator Overloading CS 3370 – C++ Chapter 14.
Operator Overloading Introduction
Yan Shi CS/SE 2630 Lecture Notes
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value A copy of the argument’s value.
Chapter 1.2 Introduction to C++ Programming
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSCE 210 Data Structures and Algorithms
Chapter 1.2 Introduction to C++ Programming
Classes (Part 1) Lecture 3
Chapter 1.2 Introduction to C++ Programming
CSS342: Objects and Classes
Chapter 1.2 Introduction to C++ Programming
C++ Templates.
Introduction to C++ Systems Programming.
A First C++ Class – a Circle
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
classes and objects review
Class: Special Topics Copy Constructors Static members Friends this
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Chapter 14: More About Classes.
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Introduction to Classes
Chapter 5 Function Basics
Advanced Program Design with C++
CS150 Introduction to Computer Science 1
CISC/CMPE320 - Prof. McLeod
From C to C++: Summary of weeks 1 - 4
COMS 261 Computer Science I
COP 3330 Object-oriented Programming in C++
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Development and Implementation
Class rational part2.
Lists CMSC 202, Version 4/02.
Object Oriented Programming
Presentation transcript:

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Lecture 2. 141004. Carrano CH1, C++ Interlude 1.1-1.2, C++ Interlude 5 C++ Book

Agenda Program 1 Discussion Deck of Cards: Class Design Encapsulation Flush out card deck examples friends Constructors Call by Reference Overloading Operators: Rational Class

Program 1 Can I get away with a single constructor? Where should I place const definitions? What do I need to turn in?

Class Design Simple Complete Cohesive Descriptive Intuitive Minimal No Public Data Amenable to loosely couple

Problem 2 Design an interface for a class representing a deck of playing cards

#include "Card.h" #include "Hand.h" const int CARDS_IN_DECK = 52; class Deck { public: Deck(); ~Deck(); Card DealSingleCard(); Hand DealHand(int number); void Shuffle(); void Cut(); int CountCardsRemaining(); void ReturnHand(Hand theHand); void ReturnCard(Card theCard); int CountValuesRemaining(int val); int CountSuitsRemaing(Suit suit); bool isEmpty(); bool isComplete(); private: Card deck[CARDS_IN_DECK]; };

Interface Design Checklist Constructors Setters/Getters Actions (verbs) Operator Overloads Private Data Types

Why C++ Object Oriented Programming (OOP)? Abstraction <- Last Time Encapsulation <- This Time Hierarchy Polymorphism

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. Implementation of method S Program that uses method 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 data Data Structures: a construct within a programming language that stores a collection of data Behave as a new data type add remove query Examples: student lists rational numbers complex numbers currency (cents/dollars) length measurement (inches/feet) weight measurement (oz/lbs) Program that uses a class

Encapsulation at ground level Program consists of Driver file (main) – keep this quite small Classes (ex, MyClass) MyClass.h -- interface MyClass.cpp -- implementation Interface (.h file) public: functions called by others private: data, helper functions Implementation (.cpp file) MyClass::function()

Examples of private data Flush out deck example const int CARDS_IN_DECK = 52; class Deck { public: Deck(); Card DealSingleCard(); Hand DealHand(int number); ….interface as defined last time…. ~Deck(); private: Card deck[52]; }; enum Suit { Heart, Diamond, Club, Spade }; class Card { public: Card(); Card(int val, Suit suit); ~Card(); private: int value; Suit suit; };

Friends Declared on either functions or classes Identified with the friend keyword Non-member functions can access private data of an object if it has been declared a friend Friendship is not transitive (my friend’s friend is not my friend) Violates encapsulation class Foo { friend class TheClassToGrantAccess; public: private: }

Constructor Uses same name as class is constructs Nothing returned; not even void Default constructor created Function executed on creation of object Arrays: constructors called in increasing order Arr[0], Arr[1], Arr[2],… Signature chooses constructor Casting of call parameters done using normal casting rules What’s in a constructor? Normally used initialize private data as built-in types in C++ are undefined (int a; a is unknown state) Generally side-effecting is not done

Add constructor(s) to Card How about GETTERS/SETTERS?

CONST keyword usages Global definition of value which does not change const int NUM_CARDS_IN_DECK = 52 (can also be done with preprocess #define but do not use) Modifier on member function which does not change data in object void MyFuntion(int p) const; const reference to save space on passing in variable void MyFunction(const MyParamType &mpt); There are other usages but the above are the most common/useful

Computer Scientist of the Week Presper Eckert Chief Engineer first general purpose electronic digital computer (ENIAC) Vaccuum tubes Calculated ballistic tables for artillery Presented first course in computers (Moore School Lectures) Founded first commercial computer company Designed first commercial computer, UNIVAC Designed Von Neumann Architecture

C++ Fundamentals LET’S CODE

string http://www.cprogramming.com/tutorial/string.html Mutable; Copied not shared. string firstName = "jimmy"; string lastName("hoffa"); string fullName; fullName = firstName + " " + lastName; cout << fullName << endl; cout << "First and last letters are:" << fullName[0] << " " << fullName[fullName.length() - 1] << endl; if (fullName == "jimmy hoffa") { cout << "Found !!!! "; } else cout << "oh where oh where have you gone";

Call by Value, Reference, and Constant Reference struct Rectangle { int length; int width; }; int Area(Rectangle rect) int Area(Rectangle &rect) int Area(const Rectangle &rect) { int temp; temp = rect.length; rect.length = 35; return(temp * rect.width); } int main() { int result; Rectangle r = { 3, 3 }; result = Area(r); cout << "length = " << r.length << endl; cout << "width = " << r.width << endl; cout << "Area = " << result << endl; return 0; }

Class Bell

In class code Write a function which takes two integers and “swaps” them

Call by Value, Reference, and Constant Reference Arrays, Pointers, and Structures Call by Value, Reference, and Constant Reference Which of swap functions is appropriate? void swap(string a, string b) { string tmp = a; a = b; b = tmp; } void swap(string &a, string &b) { string tmp = a; a = b; b = tmp; } void swap(const string &a, const string &b) { string tmp = a; a = b; b = tmp; } Which of findMax functions is appropriate? int findMax(vector<int> a) { int max = a[0]; int i; for (i=1; i < a.size(); i++) if (a[i] > max) max = a[i]; return max; } int findMax(vector<int> &a) { int max = a[0]; int i; for (i=1; i < a.size(); i++) if (a[i] > max) max = a[i]; return max; } int findMax(const vector<int> &a) { int max = a[0]; int i; for (i=1; i < a.size(); i++) if (a[i] > max) max = a[i]; return max; } CSS342: Introduction

Rational Class Create a class to represent a rational number

Rational Class Create a class to represent a rational number This should allow for multiplication, division, addition, subtraction. Comparison (eg, ==, !=) Printing out to stream

Interface Design Checklist Constructors Setters/Getters Actions (verbs) Operator Overloads Private Data Types

Rational.h: w/o Operating Overloads #include <iostream> #include <algorithm> using namespace std; class Rational { public: Rational(); Rational(int num, int den); ~Rational(); int getNumerator() const; int getDemnominator() const; bool setValue(int num, int den); Rational Multiply(const Rational &rat) const; Rational Divide(const Rational &rat) const; Rational Subtract(const Rational &rat) const; Rational Add(const Rational &rat) const; void PrintRational(ostream &theStream) const; private: int numerator; int denominator; void reduce(); };

Rational.cpp: w/o Operator Overloading Rational::Rational() { numerator = 0; denominator = 1; } Rational::Rational(int num, int den) numerator = num; denominator = den; reduce(); int Rational::getNumerator() const return numerator; int Rational::getDemnominator() const return denominator; bool Rational::setValue(int num, int den) { if (den == 0) return false; } numerator = num; denominator = den; reduce(); return true;

Rational.cpp: w/o Operator Overloading void Rational::reduce() { int gcd = 1; int minimum = min(numerator, denominator); for (int i = 2; i <= minimum; i++) if (((numerator % i) == 0) && ((denominator % i) == 0)) gcd = i; } if (gcd > 1) numerator /= gcd; denominator /= gcd; Rational Rational::Multiply(const Rational &rat) const { Rational temp; temp.numerator = numerator * rat.numerator; temp.denominator = denominator * rat.denominator; temp.reduce(); return temp; } Rational Rational::Add(const Rational &rat) const { Rational temp; temp.numerator = (numerator * rat.denominator) + (rat.numerator * denominator); temp.denominator = denominator * rat.denominator; temp.reduce(); return temp; }

Operator Overload Allowing for operators to work on classes in intuitive ways. Key Examples: Arithmetic: +, -, *, / Comparison: ==, !=, <, >, <=, >= Input: <<, >> General rules for overloading Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded Always stick to the operator’s well-known semantics Always provide all out of a set of related operations Operators retain their precedence order

Overloading +,-,*,/ as member functions class Rational { public: // Op Overloads Rational operator*(const Rational &rat) const; Rational operator/(const Rational &rat) const; Rational operator-(const Rational &rat) const; Rational operator+(const Rational &rat) const; };

Overloading input/output <<, >> class Rational { public: friend ostream& operator<<(ostream &outStream, const Rational &rat); friend istream& operator>>(istream &inStream, Rational &rat); // Op Overloads Rational operator*(const Rational &rat) const; Rational operator/(const Rational &rat) const; Rational operator-(const Rational &rat) const; Rational operator+(const Rational &rat) const;

Overloading ==, !=, +=, etc… class Rational { friend ostream& operator<<(ostream &outStream, const Rational &rat); friend istream& operator>>(istream &inStream, Rational &rat); public: // Op Overloads Rational operator*(const Rational &rat) const; Rational& operator*=(const Rational &rat); Rational operator/(const Rational &rat) const; Rational& operator/=(const Rational &rat); Rational operator-(const Rational &rat) const; Rational& operator-=(const Rational &rat); Rational operator+(const Rational &rat) const; Rational& operator+=(const Rational &rat); bool operator==(const Rational &rat) const; bool operator!=(const Rational &rat) const;

But wait… Given we overloaded +, is there a better way to implement +=? Actually, one should implement += first, and then used it to implement + Same for -=/-, *=/*, and / /=

Using += overload to implement + MyClass & MyClass::operator+=(const MyClass &rhs) { ... // Do the compound assignment work. return *this; } MyClass MyClass::operator+(const MyClass &other) const MyClass result = *this; result += other; return result;

Resources on overloading. http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html http://courses.washington.edu/css342/dimpsey/ProgramExamples/code.html -- rational class