A Computer Science Tapestry 6.1 Classes: From Use to Implementation l We’ve used several classes, a class is a collection of objects sharing similar characteristics.

Slides:



Advertisements
Similar presentations
CS201 – Introduction to Computing – Sabancı University 1 First Midterm Exam l November 22, 2008, Saturday, 10:40 – 12:20, max 100 minutes l One A4 size.
Advertisements

COMP171 Data Structures and Algorithm Tutorial 2 TA: M.Y.Chan.
Announcements Homework 4 – Robot game is assigned Due NEXT WEEK on Wednesday 26 th November  Start EARLY! Common Questions: Be aware of the flow of the.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Software Testing and Quality Assurance
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
Classes: From Use to Implementation
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Using, Understanding, Updating, Designing and Implementing Classes Chapters 5 (5.4) and partially 6 and 7 in Chapter 6, up to in Chapter 7 concepts.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
Programming Logic and Design Using Methods. 2 Objectives Review how to use a simple method with local variables and constants Create a method that requires.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Announcements Midterm1 is on this Tuesday at 19:40. Classrooms as follows: if (LastName
38 4/11/98 CSE 143 Modules [Chapter 2]. 39 4/11/98 What is a Module?  Collection of related items packaged together  Examples:  Stereo System Components.
CS201 – Introduction to Computing – Sabancı University 1 First Midterm Exam l November 25, 2006, Saturday, 10:40 – 12:20, max 100 minutes l Exam Places.
C++ Classes and Data Structures Jeffrey S. Childs
Session 7 Methods Strings Constructors this Inheritance.
Reference parameters (6.2.3) We might need a function to return more than one value Find roots of a quadratic 2 return values. What are they? Get first.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
1 CSC 222: Computer Programming II Spring 2004  classes and objects  abstract data types, classes and objects  using existing classes, #include, member.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 CMSC 202 ADTs and C++ Classes. 2 Announcements Project 1 due Sunday February 25 th at midnight – don’t be late! Notes and clarifications for Project.
CS201 – Introduction to Computing – Sabancı University 1 Using, Understanding, Updating, Designing and Implementing Classes l Chapters 5 (5.4) and partially.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
1 Introduction to Object Oriented Programming Chapter 10.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Classes: Defining Your Own Data Types Basic principles in OOP Define a new data type as a class and use objects of a class Member Functions –Constructors.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
C++ Functions A bit of review (things we’ve covered so far)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Classes and OOP.
Review: Two Programming Paradigms
Announcements Homework 5 – Robot game will be assigned this week
Introduction to Classes
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Announcements Homework 5 – Robot game will be assigned this week
Topics Decomposition Parameter passing Reading and writing from files
Reference parameters (6.2.3)
Introduction to Classes
Using, Understanding, Updating, Designing and Implementing Classes
Chapter 9 Introduction To Classes
Classes: From Use to Implementation
(4 – 2) Introduction to Classes in C++
Classes: From Use to Implementation
Presentation transcript:

A Computer Science Tapestry 6.1 Classes: From Use to Implementation l We’ve used several classes, a class is a collection of objects sharing similar characteristics  A class is a type in C++, like int, bool, double ä A class encapsulates state and behavior ä A class is an object factory string (this is a standard class), need #include  Objects: " hello ", " there are no frogs ", …  Methods: substr(…), length(…), find(…), << Date need #include " date.h " ä Objects: December 7, 1949, November 22, 1963  Methods: MonthName(), DaysIn(), operator -

A Computer Science Tapestry 6.2 Anatomy of the Dice class The class Dice, need #include " dice.h " ä Objects: six-sided dice, 32-sided dice, one-sided dice  Methods: Roll(), NumSides(), NumRolls() l A Dice object has state and behavior ä Each object has its own state, just like each int has its own value Number of times rolled, number of sides ä All objects in a class share method implementations, but access their own state How to respond to NumRolls()? Return my own # rolls

A Computer Science Tapestry 6.3 The header file dice.h class Dice { public: Dice(int sides); // constructor int Roll(); // return the random roll int NumSides() const; // how many sides int NumRolls() const; // # times this die rolled private: int myRollCount; // # times die rolled int mySides; // # sides on die }; The compiler reads this header file to know what’s in a Dice object Each Dice object has its own mySides and myRollCount

A Computer Science Tapestry 6.4 Anatomy of a header file

A Computer Science Tapestry 6.5 The header file is a class declaration l What the class looks like, but now how it does anything l Private data are called instance variables ä Sometimes called data members, each object has its own l Public functions are called methods, member functions, these are called by client programs l The header file is an interface, not an implementation ä Description of behavior, analogy to stereo system ä Square root button, how does it calculate? Do you care? l Information hiding and encapsulation, two key ideas in designing programs, object-oriented or otherwise

A Computer Science Tapestry 6.6 From interface to use, the class Dice #include “dice.h” int main() { Dice cube(6); Dice dodeca(12); int x = cube.Roll(); int k; for(k=0; k < 6; k++) { x = dodeca.Roll(); } return 0; } Objects constructed cube.myRollCount == 0 cube.mySides == 6 dodeca.myRollCount == 0 dodeca.mySides == 12 Method invoked After for loop cube.myRollCount == 1 cube.mySides == 6 dodeca.myRollCount == 6 dodeca.mySides == 12

A Computer Science Tapestry 6.7 Header file as Interface l Provides information to compiler and to programmers ä Compiler determines how big an object (e.g., Dice cube(6)) is in memory ä Compiler determines what methods/member functions can be called for a class/object ä Programmer reads header file (in theory) to determine what methods are available, how to use them, other information about the class l What about CD, DVD, stereo components? ä You can use these without knowing how they really work ä Well-designed and standard interface makes it possible to connect different components ä OO software strives to emulate this concept

A Computer Science Tapestry 6.8 William H. (Bill) Gates, (b. 1955) l CEO of Microsoft, richest person in the world (1999) ä First developed a BASIC compiler while at Harvard ä Dropped out (asked to leave?) went on to develop Microsoft “ You’ve got to be willing to read other people’s code, then write your own, then have other people review your code ” l Generous to Computer Science and philanthropic in general l Visionary, perhaps cutthroat

A Computer Science Tapestry 6.9 From Interface to Implementation l The header file provides compiler and programmer with how to use a class, but no information about how the class is implemented ä Important separation of concerns, use without complete understanding of implementation ä Implementation can change and client programs won’t (hopefully) need to be rewritten If private section changes, client programs will need to recompile If private section doesn’t change, but implementation does, then client programs relinked, but not recompiled l The implementation of foo.h is typically in foo.cpp, this is a convention, not a rule, but it’s well established (foo.cc used too)

A Computer Science Tapestry 6.10 Implementation, the.cpp file l In the implementation file we see all member functions written, same idea as functions we’ve seen so far ä Each function has name, parameter list, and return type ä A member function’s name includes its class ä A constructor is a special member function for initializing an object, constructors have no return type Dice::Dice(int sides) // postcondition: all private fields initialized { myRollCount = 0; mySides = sides; } int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; }

A Computer Science Tapestry 6.11 More on method implementation l Each method can access private data members of an object, so same method implementation shared by different objects  cube.NumSides() compared to dodeca.NumSides() int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; } int Dice::Roll() // postcondition: number of rolls updated // random 'die' roll returned { RandGen gen; // random number generator (“randgen.h”) myRollCount= myRollCount + 1; // update # of rolls return gen.RandInt(1,mySides); // in range [1..mySides] }

A Computer Science Tapestry 6.12 Understanding Class Implementations l You do NOT need to understand implementations to write programs that use classes ä You need to understand interfaces, not implementations ä However, at some point you’ll write your own classes l Data members are global or accessible to each class method l Constructors should assign values to each instance variable l Methods can be broadly categorized as accessors or mutators ä Accessor methods return information about an object Dice::NumRolls() and Dice::NumSides() ä Mutator methods change the state of an object Dice::Roll(), since it changes an object’s myNumRolls

A Computer Science Tapestry 6.13 Class Implementation Heuristics l All data should be private  Provide accessor functions as needed, although classes should have more behavior than simple GetXXX methods Make accessor functions const  Easy to use const functions (we’ll see more on const later), although difficult at times to implement properly  A const function doesn’t modify the state of an object int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; }

A Computer Science Tapestry 6.14 Building Programs and Classes l To develop a program, written with classes or not, start small ä Get a core working, and add to the core ä Keep the program working, easier to find errors when you’ve only a small amount of new functionality ä Grow a program incrementally rather than building a program all at once l Start with a prototype ä Incomplete, but reasonable facsimile to the final project ä Help debug design, ideas, code, … ä Get feedback to stay on track in developing program From users, from compiler, from friends, from yourself

A Computer Science Tapestry 6.15 Design Heuristics l Make each function or class you write as single-purpose as possible ä Avoid functions that do more than one thing, such as reading numbers and calculating an average, standard deviation, maximal number, etc., If source of numbers changes how do we do statistics? If we want only the average, what do we do? ä Classes should embody one concept, not several. The behavior/methods should be closely related l This heuristic is called Cohesion, we want functions and classes to be cohesive, doing one thing rather than several ä Easier to re-use in multiple contexts

A Computer Science Tapestry 6.16 Design Heuristics continued l Functions and classes must interact to be useful ä One function calls another  One class uses another, e.g., as the Dice::Roll() function uses the class RandGen l Keep interactions minimal so that classes and functions don’t rely too heavily on each other, we want to be able to change one class or function (to make it more efficient, for example) without changing all the code that uses it l Some coupling is necessary for functions/classes to communicate, but keep coupling loose ä Change class/function with minimal impact

A Computer Science Tapestry 6.17 Reference parameters l It’s useful for a function to return more than one value ä Find roots of a quadratic ä Get first and last name of a user l Functions are limited to one return value ä Combine multiple return values in object (create a class) ä Use reference parameters to send values back from function Values not literally returned Function call sends in an object that is changed Sometimes caller wants to supply the object that’s changed string s = ToLower("HEllO") // return type? string s = "HeLLo"; ToLower(s); // return type?

A Computer Science Tapestry 6.18 Quadratic Equation Example void Roots(double a, double b, double c, double& root1, double& root2); // post: root1 and root2 set to roots of // quadratic ax^2 + bx + c // values undefined if no roots exist int main() { double a,b,c,r1,r2; cout << "enter coefficients "; cin >> a >> b >> c; Roots(a,b,c,r1,r2); cout << "roots are " << r1 << " " << r2 << endl; return 0; }

A Computer Science Tapestry 6.19 Who supplies memory, where’s copy? void Roots(double a, double b, double c, double& root1, double& root2); // post: root1 and root2 set to roots of // quadratic ax^2 + bx + c // values undefined if no roots exist l For value parameter, the argument value is copied into memory that “belongs” to parameter l For reference parameter, the argument is the memory, the parameter is an alias for argument memory double x, y, w, z; Roots(1.0, 5.0, 6.0, x, y); Roots(1.0, w, z, 2.0, x); // no good, why?

A Computer Science Tapestry 6.20 Examples l What’s prototype for a function that rolls two N-sided dice Y times and returns the number of double 1’s and double N’s l What’s prototype for a function that returns the number of hours, minutes, and seconds in N seconds? l What’s prototype for a function that returns the number of Saturdays and the number of Sundays in a year?