Defining New Types Lecture 21 Hartmut Kaiser

Slides:



Advertisements
Similar presentations
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Advertisements

1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Road Map Introduction to object oriented programming. Classes
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Lecture 9 Concepts of Programming Languages
Abstract Data Types and Encapsulation Concepts
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Review of C++ Programming Part II Sheng-Fang Huang.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Organizing Programs and Data 2 Lecture 7 Hartmut Kaiser
Organizing Programs and Data Lecture 5 Hartmut Kaiser
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Object-Oriented Programming in C++
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
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.
Learners Support Publications Classes and Objects.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Working with Batches of Data Lecture 4 Hartmut Kaiser
Looping and Counting Lecture 3 Hartmut Kaiser
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Writing Generic Functions Lecture 20 Hartmut Kaiser
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
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?
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Using Sequential Containers Lecture 8 Hartmut Kaiser
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
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.
1 Data Structures CSCI 132, Spring 2014 Lecture 2 Classes and Abstract Data Types Read Ch Read Style Guide (see course webpage)
Chapter 4 Organizing Programs and Data. Objectives Understand the use of functions in dividing a program into smaller tasks. Discover how parameters can.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 2 Objects and Classes
Procedural and Object-Oriented Programming
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?
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Introduction to Classes
Organizing Programs and Data 2
Introduction to Classes
Classes and Data Abstraction
Defining New Types Lecture 22 Hartmut Kaiser
Classes and Objects.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Defining New Types Lecture 21 Hartmut Kaiser

Programming Principle of the Day Hide Implementation Details  Hiding implementation details allows change to the implementation of a code component while minimally affecting any other modules that use that component.  Encapsulation is key  A language mechanism for restricting access to some of the object's components  A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 2

Defining New Types C++ has two kinds of types  built-in types  int, double, char, etc.  class types (user defined types)  string, vector, istream  Rely entirely on built-in types and other class types and generally available language facilities Design of C++ rests on the idea of creating user defined types usable similar to built-in types  Requires substantial language support  Taste and judgment in class design 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 3

student_info Type Revisted We wrote the student_info type and related functions  However, these were not well suited for other programmers to use  Any newly created student_info object required first to read data into it  Otherwise the values would have been uninitialized  No way to check whether held data was valid  Well, without looking at member values  Requires internal knowledge of student_info  Assumption was that after grades were read they wouldn’t change  Interface to student_info was scattered (separate, unrelated functions) 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 4

Class (User Defined) Types Class types allow to group several data items into one entity That’s what we used: struct student_info { std::string name; double midterm, final; std::vector homework; }; Four data elements: data members  A string, two double’s, and a vector 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 5

Class (User Defined) Types Programmers may – and must – handle those data items directly  They may – because nothing is preventing them  They must – because there is no other way It would be better to hide implementation details of how things are stored  Manipulate members through functions only  This forms the interface of our class 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 6

Class (User Defined) Types Important general remarks  Always use fully qualified names in headers  There is no guarantee that a using directive is in effect  But adding a using directive yourself to a header might break other code  Never put a using directive into a header 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 7

Member Functions Let’s start with adding interface function to read the student grades and to calculate the overall grade: struct student_info { std::string name; double midterm, final; std::vector homework; std::istream& read(std::istream&); // added double grade() const; // added }; We added two member functions  The ‘const’ means, that grade will not change any members 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 8

Member Functions A member function is a function that is a member of a class object  We have already seen those (v.size(), v.begin(), etc.) In order to call a member function, our users must nominate the object of which the function to be called is a member: student_info s; s.read(cin); // calling ‘read()’ for object instance ‘s’ cout << s.grade(); // calling ‘grade()’ for ‘s’ 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 9

Member Functions Member function implementation: istream& student_info::read(istream& in) { in >> name >> midterm >> final; read_hw(in, homework); return in; } The name of the function is different  It’s student_info::read instead of plain read This function is a member of a student_info object  No need to pass a student_info object as an argument We access the data elements of our object directly  Instead to s.midterm we refer to just midterm. 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 10

Member Function Specifics student_info::read instead of read  ‘::’ scoping operator (like in string::size_type)  That means read is now part of student_info, i.e. a member function  No need to pass a student_info object as an argument  The student_info instance is implicit for every call  The instance we want to invoke the function for is specified using the dot-notation: student_info s; s.read(cin); 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 11

Member Function Specifics The references to the members inside read are unqualified  They are references to members of the object instance on which we are operating  If we call s.read(cin) for a student_info object named s, then we are operating on object s.  When read() uses midterm, final, and homework, it will be using s.midterm, s.final, and s.homework respectively 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 12

Member Functions Member function implementation: double student_info::grade() const { return ::grade(midterm, final, homework); } Same considerations: name, implicit student_info instance, and unqualified members Using ‘::’ in front of a name forces using a version of that name in global namespace  Without it the compiler would refer to student_info::grade itself, resulting in a compilation error (why?) 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 13

Member Function Constness Appended const – why do we need it? // original double grade(student_info const&) {... } // member-function version double student_info::grade() const {... }   const member function  Does not change any of the members  This const is part of the function signature  Needs to be specified for the declaration and the definition 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 14

Protection Users of student_info do not need to manipulate the data members of our class  But they still could! Hide the data members (make them inaccessible): class student_info { public: // interface goes here double grade() const; std::istream& read(std::istream&); private: // implementation goes here std::string name; double midterm, final; std::vector homework; }; 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 15

Protection class instead struct  Essentially, 100% equivalent  Different defaults in terms of accessibility of members Protection labels (key words): ‘public’, ‘private’  Public: accessible by non-members  Private: not accessible by non-members 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 16

Accessor Functions We hid data members from modification but also from reading :-P Let’s make name available again: class student_info { public: // interface goes here double grade() const; std::istream& read(std::istream&); std::string name() const { return n; } // added! private: // implementation goes here std::string n; // name change! double midterm, final; std::vector homework; }; 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 17

Comparing student_info Instances In order to compare (sort!) student_info instances we need to rewrite compare(): bool compare(student_info const& x, student_info const& y) { return x.name() < y.name(); } Still a global function Nevertheless it’s part of the interface of student_info: add it to the same header file 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 18

Checking for Validity This code will throw (why?): student_info s; cout << s.grade() << endl; // exception: s has no data We need a way to check whether a student_info instance ‘is valid’ (has homework): class student_info { public: bool valid() const { return !homework.empty(); } //...as before }; Allows to check before calling grade 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 19

Constructors What happens when objects are created?  Constructor is called – leaves object in defined state Special member functions that define how objects are initialized  No way to call a constructor explicitly  Called automatically by the compiler whenever object instance is created If no constructor is defined, compiler synthesizes one (default constructor) which calls the default constructors of all members 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 20

Constructors We define 2 constructors  Default constructor (no argument)  Construct from istream class student_info { public: // construct an empty student_info object student_info(); // construct one by reading from a stream student_info(std::istream&); //... as before }; 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 21

The default Constructor No argument constructor is called ‘default constructor’: student_info::student_info() : midterm(0), final(0) {} Initialize built in data types  Otherwise would contain garbage Compiler (default) initializes all class types, but could be explicit: student_info::student_info() : n(), midterm(0), final(0), homework() {} 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 22

The Constructor (any Constructor) When we create a new class object, several steps happen in sequence: 1.The implementation allocates memory to hold the object. 2.It initializes the object, as directed by the constructor's initializer list. 3.It executes the constructor body. Initialization of all members happens before the constructor body begins execution  Regardless whether there is a initializer list or not 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 23

Constructors with Arguments Any constructor can take arguments allowing to initialize the object in different ways: student_info::student_info(std::istream& is) { read(is); } Even if there is no initializer list, ‘n’ and ‘homework’ are default constructed before body is executed 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 24

Using the New student_info Class int main() { vector students; student_info record; string::size_type maxlen = 0; // read and store the data while (record.read(cin)) { // changed maxlen = max(maxlen, record.name().size()); // changed students.push_back(record); } // alphabetize the student records sort(students.begin(), students.end(), compare); //... } 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 25

Using the New student_info Class // write the names and grades for (vector ::size_type i = 0; i != students.size(); ++i) { cout << students[i].name() // changed << string(maxlen students[i].name().size(), ' '); try { double final_grade = students[i].grade(); // changed streamsize prec = cout.precision(); cout << setprecision(3) << final_grade << setprecision(prec) << endl; } catch (domain_error e) { cout << e.what() << endl; } return 0; 4/2/2015 Lecture 21 CSC 1254, Spring 2015, Defining New Types 26