CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Abstract Data Types

Similar documents
CS 103 Unit 10 Slides

CS 103 Unit 10 Slides

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

CS 103 Unit 14. Classes Revisited. Mark Redekopp

Chapter 10 Introduction to Classes

Lecture 18 Tao Wang 1

Topic 10: Introduction to OO analysis and design

Methods. Methods. Mysteries Revealed

Chapter 4 Defining Classes I

G52CPP C++ Programming Lecture 9

CS 101: Computer Programming and Utilization

CSC1322 Object-Oriented Programming Concepts

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

Introduction to Classes

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Array Basics: Outline

CSCI 104 Inheritance. Mark Redekopp David Kempe

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Chapter 6 Structures and Classes. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

CMPT 117: Tutorial 1. Craig Thompson. 12 January 2009

Array Basics: Outline

An Introduction to C++

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

QUIZ Friends class Y;


Lecture 7. Log into Linux New documents posted to course webpage

Scope. Scope is such an important thing that we ll review what we know about scope now:

Special Member Functions

Classes and Objects. Class scope: - private members are only accessible by the class methods.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

A A B U n i v e r s i t y

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Encapsula)on CMSC 202

C++ Overview (1) COS320 Heejin Ahn

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

CS24 Week 3 Lecture 1

Short Notes of CS201

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

CS201 - Introduction to Programming Glossary By

Func%ons. CS449 Fall 2017

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Mo#va#ng the OO Way. COMP 401, Fall 2017 Lecture 05

2 ADT Programming User-defined abstract data types

ADTs & Classes. An introduction

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Topics. Topics (Continued) 7.1 Abstract Data Types. Abstraction and Data Types. 7.2 Object-Oriented Programming

CSCI 104 Inheritance. Mark Redekopp David Kempe

CS201 Latest Solved MCQs

Cpt S 122 Data Structures. Introduction to C++ Part II

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

Classes in C++98 and C++11

Fundamental Concepts and Definitions

Object-Oriented Design (OOD) and C++

CS201 Some Important Definitions

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Intermediate Programming & Design (C++) Classes in C++

5. Defining Classes and Methods

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Programming Languages and Techniques (CIS120)

CS304 Object Oriented Programming Final Term

Object Oriented Design

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Objec,ves. Review: Object-Oriented Programming. Object-oriented programming in Java. What is OO programming? Benefits?


Classes. OOP & Class Object Terminology File Management

Array Basics: Outline

Problem Solving with C++

Recharge (int, int, int); //constructor declared void disply();

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

Lecture #1. Introduction to Classes and Objects

Programming II (CS300)

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

Writing a Fraction Class

Programming II (CS300)

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Object-Oriented Programming

Chapter 11. Abstract Data Types and Encapsulation Concepts

Abstraction in Software Development

Implementing an ADT with a Class

More class design with C++ Starting Savitch Chap. 11

UNIT III (PART-II) & UNIT IV(PART-I)

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Transcription:

CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 8: Abstract Data Types

Object- Oriented Programming Model the applica6on/so9ware as a set of objects that interact with each other Objects fuse data (i.e. variables) and func6ons (a.k.a methods) that operate on that data into one item (i.e. object) Like structs but now with associated func6ons/methods Objects become the primary method of encapsula6on and abstrac6on Encapsula6on Hiding of data and implementa6on details (i.e. make so9ware modular) Only expose a well- defined interface to anyone wan6ng to use our object Abstrac6on How we decompose the problem and think about our design rather than the actual code

3 Classes Object- oriented design (OOD): a problem solving methodology Objects: components of a solu6on Class: a collec6on of a fixed number of components Member: a component of a class

4 Classes Class defini6on: Defines a data type; no memory is allocated Don't forget the semicolon a9er the closing brace Syntax:

5 Classes Class member can be a variable or a func6on If a member of a class is a variable It is declared like any other variable You cannot ini6alize a variable when you declare it If a member of a class is a func6on Func6on prototype is listed Func6on members can (directly) access any member of the class

6 Classes Three categories of class members: private (default) Member cannot be accessed outside the class public Member is accessible outside the class protected

7 Unified Modeling Language Class Diagrams Unified Modeling Language (UML) nota6on: used to graphically describe a class and its members +: member is public -: member is private #: member is protected

8 Unified Modeling Language

9 Variable (Object) Declara6on Once defined, you can declare variables of that class type clocktype myclock; clocktype yourclock; A class variable is called a class object or class instance

10 Accessing Class Members Once an object is declared, it can access the public members of the class Syntax: The dot (.) is the member access operator If an object is declared in the defini6on of a member func6on of the class, it can access the public and private members

11 Built- in Opera6ons on Classes Most of C++ s built- in opera6ons do not apply to classes Arithme6c operators cannot be used on class objects unless the operators are overloaded Cannot use rela6onal operators to compare two class objects for equality Built- in opera6ons that are valid for class objects: Member access (.) Assignment (=)

12 Assignment Operator and Classes

13 Class Scope A member of the class is local to the class Can access a class member outside the class by using the class object name and the member access operator (.)

14 Func6ons and Classes Objects can be passed as parameters to func6ons and returned as func6on values As parameters to func6ons Objects can be passed by value or by reference If an object is passed by value Contents of data members of the actual parameter are copied into the corresponding data members of the formal parameter

15 Implementa6on of Member Func6ons

16 Reference Parameters and Class Objects (Variables) Pass by reference is an efficient way to pass a variable as a parameter Problem: when passing by reference, the actual parameter changes when formal parameter changes Solu6on: use const in the formal parameter declara6on

17 Unified Modeling Language

18 Implementa6on of Member Func6ons myclock.equaltime(yourclock);

19 Implementa6on of Member Func6ons Once a class is properly defined and implemented, it can be used in a program A program that uses/manipulates objects of a class is called a client of that class When you declare objects of the class clocktype, each object has its own copy of the member variables (hr, min, and sec) Called instance variables of the class Every object has its own instance of the data

20 Accessor and Mutator Func6ons Accessor func6on: member func6on that only accesses the value(s) of member variable(s) Mutator func6on: member func6on that modifies the value(s) of member variable(s) Constant func6on: Member func6on that cannot modify member variables Use const in func6on heading

21 Order of public and private Members of a Class C++ has no fixed order in which to declare public and private members By default, all members of a class are private Use the member access specifier public to make a member available for public access

22 Constructors Use constructors to guarantee that member variables of a class are ini6alized Two types of constructors: With parameters Without parameters (default constructor) Name of a constructor = name of the class A constructor has no type

23 Constructors A class can have more than one constructor Each must have a different formal parameter list Constructors execute automa6cally when a class object enters its scope They cannot be called like other func6ons Which constructor executes depends on the types of values passed to the class object when the class object is declared

24 Constructors clocktype() { hr=0; min=0; sec=0; clocktype(int hour, int minutes, int seconds) { hr=hour; min=minutes; sec=seconds;

25 Invoking a Constructor A constructor is automa6cally executed when a class variable is declared Because a class may have more than one constructor, you can invoke a specific constructor

26 Invoking the Default Constructor To invoke the default constructor: Example: clocktype yourclock;

27 Invoking a Constructor with Parameters clocktype myclock(14,8,25); Number and type of arguments should match the formal parameters (in the order given) of one of the constructors Otherwise, C++ uses type conversion and looks for the best match Any ambiguity causes a compile- 6me error

28 Arrays of Class Objects (Variables) and Constructors If you declare an array of class objects, the class should have the default constructor

29 Classes and Constructors: A Precau6on If a class has no constructor(s), C++ provides the default constructor However, object declared is s6ll unini6alized If a class includes constructor(s) with parameter(s), but not the default constructor C++ does not provide the default constructor

30 Destructors Destructors are func6ons without any type The name of a destructor is the character '~' followed by class name For example: ~clocktype(); A class can have only one destructor The destructor has no parameters Destructor automa6cally executes when the class object goes out of scope

31 A struct Versus a class By default, members of a struct are public private specifier can be used in a struct to make a member private By default, the members of a class are private classes and structs have the same capabili6es

32 A struct Versus a class In C++, the defini6on of a struct was expanded to include member func6ons, constructors, and destructors If all member variables of a class are public and there are no member func6ons Use a struct

33 Classes and Abstract Data Types Abstrac6on Separa6ng design details from usage Separa6ng the logical proper6es from the implementa6on details Abstrac6on can also be applied to data Abstract data type (ADT): data type that separates the logical proper6es from the implementa6on details

34 Informa6on Hiding Information hiding: hiding the details of the operations on the data Interface (header) file: contains the specification details File extension is.h Implementation file: contains the implementation details File extension is.cpp In header file, include function prototypes and comments that briefly describe the functions Specify preconditions and/or postconditions

35 Informa6on Hiding Implementa6on file must include header file via include statement In include statement: User- defined header files are enclosed in double quotes System- provided header files are enclosed between angular brackets

36 Implementa6on of Member Func6ons Must write the code for func6ons defined as func6on prototypes Prototypes are le9 in the class to keep the class smaller and to hide the implementa6on To access iden6fiers local to the class, use the scope resolu6on operator ::

Example: Deck of cards Objects contain: Data members Data needed to model the object and track its state/ operation (just like structs) Methods/Functions Code that operates on the object, modifies it, etc. Deck Data members: Array of 52 entries (one for each card) indicating their ordering Top index Deck Methods/Functions Shuffle(), Cut(), Get_top_card()

UML (Unified Modeling Language) class name (e.g. Deck) Member functions + shuffle() : void + cut() : void + get_top_card() : int - cards[52] : int - top_index : int Member data class Deck { public: Deck(); // Constructor ~Deck(); // Destructor void shuffle(); void cut(); int get_top_card(); private: int cards[52]; int top_index; ;

C++ Classes Programming construct used to define objects, their data members, and methods/functions Similar idea to structs Steps: Define the class data members and method prototypes (usually in a separate header file) Write the methods in a separate.cpp file Instantiate/Declare object variables and use them by calling their methods Terminology: Class = Definition/Blueprint of an object Object = Instance of the class, actual allocation of memory, variable, etc. class Deck { public: Deck(); // Constructor ~Deck(); // Destructor void shuffle(); void cut(); int get_top_card(); private: int cards[52]; int top_index; ; #include<iostream> #include deck.h // Code for each prototyped method #include<iostream> #include deck.h int main() { Deck d; int hand[5]; d.shuffle(); d.cut(); for(int i=0; i < 5; i++){ hand[i] = d.get_top_card(); deck.h deck.cpp poker.cpp

Class Definition class name { ; Each function or data member can be classified as public, private, or protected Private: Can call or access only by methods/functions that are part of that class Public: Can call or access by any other code Protected: More on this later Everything private by default so you must use public: to make things visible Make the interface public and the guts/inner-workings private class Deck { public: Deck(); // Constructor ~Deck(); // Destructor void shuffle(); void cut(); int get_top_card(); private: int cards[52]; int top_index; ; #include<iostream> #include deck.h // Code for each prototyped method #include<iostream> #include deck.h int main() { Deck d; int hand[5]; d.shuffle(); d.cut(); d.cards[0] = ACE;//won t compile d.top_index = 5; //won t compile deck.h deck.cpp poker.cpp

Constructors / Destructors Constructor is a function of the same name as the class itself It is called automatically when the object is created Use to initialize your object to desired state Returns nothing Destructor is a function of the same name as class itself with a ~ in front Called automatically when object goes out of scope Use to delete any memory allocated by the object Returns nothing class Deck { public: Deck(); // Constructor ~Deck(); // Destructor... ; #include<iostream> #include deck.h Deck::Deck() { top_index = 0; for(int i=0; i < 52; i++){ cards[i] = i; Deck::~Deck() { #include<iostream> #include deck.h int main() { Deck d; // Deck() is called... return 1; // ~Deck() is called since // function is done deck.h deck.cpp poker.cpp

Writing Member Functions When writing member functions, we must scope our functions This allows the compiler to check access to private/public variables Without the scope operator [i.e. void shuffle() rather than void Deck::shuffle() ] the compiler would think that the function is some outside function (not a member of Deck) and thus generate an error when it tried to modify the cards array. class Deck { public: Deck(); // Constructor ~Deck(); // Destructor... ; #include<iostream> #include deck.h Deck::Deck() { top_index = 0; for(int i=0; i < 52; i++){ cards[i] = i; Deck::~Deck() { void Deck::shuffle() { cut(); //calls cut() for the object... int Deck::get_top_card() { top_index++; return cards[top_index-1]; deck.h deck.cpp

Calling Member Functions Member functions are called by preceding their name with the specific object that it should operate on d1 d1.shuffle() indicates the code of shuffle() should be operating implicitly on d1 s data member vs. d2 or any other Deck object d1 cards[52] top_index cards[52] d2 0 1 2 3 4 5 6 7 top_index #include<iostream> #include deck.h int main() { Deck d1, d2; int hand[5]; d1.shuffle(); // not Deck.shuffle() or // shuffle(d), etc. 0 for(int i=0; i < 5; i++){ hand[i] = d1.get_top_card(); cards[52] top_index 0 1 2 3 4 5 6 7 0 41 27 8 39 25 4 11 17 1

Calling Member Functions Within a member function we can just call other member functions directly. d1 s data will be modified (shuffled and cut) d1 is implicitly passed to shuffle() d1 cards[52] top_index 41 27 8 39 25 4 11 17 1 cards[52] d2 0 1 2 3 4 5 6 7 top_index 0 Since shuffle was implicitly working on d1 s data, d1 is again implicitly passed to cut() #include<iostream> #include deck.h int main(int argc, char *argv[]) { Deck d1, d2; int hand[5]; d1.shuffle();... #include<iostream> #include deck.h void Deck::shuffle() { cut(); // calls cut() // for this object for(i=0; i < 52; i++){ int r = rand() % (52-i); int temp = cards[r]; cards[r] = cards[i]; cards[i] = temp; void Deck::cut() { // swap 1 st half of deck w/ 2 nd poker.cpp deck.cpp

Class Pointers Can declare pointers to classes Use -> operator to access member functions or data d1 cards[52] top_index cards[52] d2 0 1 2 3 4 5 6 7 top_index #include<iostream> #include deck.h 0 1 2 3 4 5 6 7 0 0 int main() { Deck *d1; int hand[5]; d1 = new Deck(); d1->shuffle(); for(int i=0; i < 5; i++){ hand[i] = d1->get_top_card(); delete d1; d1 cards[52] top_index 41 27 8 39 25 4 11 17 1

Class Constructors / Destructors Constructor is a function of the same name as the class itself It is called automatically when the object is created (either when declared or when allocated via new ) Use to initialize your object to desired state Returns nothing Destructor is a function of the same name as class itself with a ~ in front Called automatically when object goes out of scope (i.e. when it is deallocated by delete or when scope completes) Use to delete any memory allocated by the object Returns nothing class Deck { public: Deck(); // Constructor ~Deck(); // Destructor... ; #include<iostream> #include deck.h Deck::Deck() { top_index = 0; for(int i=0; i < 52; i++){ cards[i] = i; Deck::~Deck() { #include<iostream> #include deck.h int main() { Deck *dptr; dptr = new Deck(); // Deck() is // called dptr->shuffle(); delete dptr; // ~Deck() is called deck.h deck.cpp poker.cpp

Example Student Class Recall unlike structs where other code can access member variables, other code (nonmember functions of the class) cannot access private class members directly class Student { public: Student(); // Constructor 1 Student(string name, int id, double gpa); // Constructor 2 ~Student(); // Destructor... private: string _name; int _id; double _gpa; ; student.h #include<iostream> #include <string> int main() { Student s1; string myname; cin >> myname; s1._name = myname; //compile error...

Accessor / Mutator Methods Define public get (accessor) and set (mutator) functions to let other code access desired private data members #include<iostream> #include <string> int main() { Student s1; string myname; cin >> myname; s1.set_name(myname); string another_name; another_name = s1.get_name();... class Student { public: Student(); // Constructor 1 Student(string name, int id, double gpa); // Constructor 2 ~Student(); // Destructor string get_name(); int get_id(); double get_gpa(); void set_name(string s); void set_id(int i); void set_gpa(double g); private: string _name; int _id; double _gpa; ; string Student::get_name() { return _name; int Student:: get_id() { return _id; void Student:: set_name(string s) { _name = s; void Student:: set_gpa(double g) { _gpa = g; student.h student.cpp

Multiple Constructors Can have multiple constructors with different argument lists #include<iostream> #include <string> int main() { Student s1; // calls Constructor 1 string myname; cin >> myname; s1.set_name(myname); s1.set_id(214952); s1.set_gpa(3.67); Student s2(myname, 32421, 4.0); // calls Constructor 2 class Student { public: Student(); // Constructor 1 Student(string name, int id, double gpa); // Constructor 2 ~Student(); // Destructor string get_name(); int get_id(); double get_gpa(); void set_name(string name); void set_id(int id); void set_gpa(double gpa); private: string _name; int _id; double _gpa; ; Student::Student() { _name =, _id = 0; _gpa = 2.0; Student::Student(string name, int id, double gpa) { _name = name; _id = id; _gpa = gpa; student.h student.cpp