CSCE 121:509-512 Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 8: Classes 1 Based on slides created by Bjarne Stroustrup.

Slides:



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

Chapter 9 Technicalities: Classes, etc. Bjarne Stroustrup
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 5: Functions 1 Based on slides created by Bjarne Stroustrup.
Classes & Objects classes member data and member function access control and data hiding instantiation of objects class constructor and destructor objects.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
Flashback Technicalities: Classes, etc. Lecture 13 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.
CSCE 121: Introduction to Program Design and Concepts, Honors Dr. J. Michael Moore Spring 2015 Set 3: Objects, Types, and Values 1 Based on slides.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Defining New Types Lecture 21 Hartmut Kaiser
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
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:
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 4: Computation 1 Based on slides created by Bjarne Stroustrup.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 17: Vectors and Arrays 1 Based on slides created by Bjarne Stroustrup.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
GoodOO Programming Practice in Java © Allan C. Milne v
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
CSC 143F 1 CSC 143 Constructors Revisited. CSC 143F 2 Constructors In C++, the constructor is a special function automatically called when a class instance.
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?
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
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
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring Fall 2016 Set 10: Input/Output Streams 1 Based on slides created.
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:
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.
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.
Programming Fundamentals Enumerations and Functions.
CSCE Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 18: Vectors, Templates and Exceptions 1.
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.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 6: Miscellaneous 1 Based on slides created by Bjarne Stroustrup.
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?
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
CSE 143 Introduction to C++ [Appendix B] 4/11/98.
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?
The dirty secrets of objects
Chapter 9 Technicalities: Classes, etc.
// simple Date // guarantee initialization with constructor // provide some notational convenience struct Date {           int y, m, d;                            //
Chapter 9 Technicalities: Classes, etc.
Operator Overloading; String and Array Objects
Chapter 9 Technicalities: Classes, etc.
Chapter 9 Technicalities: Classes, etc.
Chapter 9 Technicalities: Classes, etc.
Guidelines for Writing Functions
Chapter 9 Introduction To Classes
Flashback Technicalities: Classes, etc.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Chapter 9 Technicalities: Classes, etc.
Presentation transcript:

CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 8: Classes 1 Based on slides created by Bjarne Stroustrup and Jennifer Welch

CSCE 121: Set 8: Classes User-Defined Types You can define your own type in C++ Specify the information (data) to be held by an object of that type – combination of built-in and user-defined types – elements are called data members Specify the operations that can be performed on objects of the type – called function members 2

CSCE 121: Set 8: Classes Structs One way to define your own type is with a struct: struct Date { int y, m, d; // year, month, day }; Put this definition in global scope. Don’t forget ending semicolon! Make a Date object and access its data members: Date my_birthday; my_birthday.y = 1900; my_birthday.m = 12; my_birthday.d = 8; cout << “I was born in “ << my_birthday.y << endl; 3

CSCE 121: Set 8: Classes Access Control Note that we could access (read and write) the data members of the Date object. What if we accidentally set my_birthday.m to 13? Or my_birthday.d to −5? Prevent that by labeling the data members as private: struct Date { private: int y,d,m; }; 4

CSCE 121: Set 8: Classes Functions in a Struct Since we’ve now made the data members private, we can only manipulate them through functions that are inside the struct (function members): struct Date { int year() { return y; } void set_year(int yy) { y = yy; } // similarly for month and day private: int y, d, m; };... Date my_birthday; my_birthday.set_year(1900); cout << “I was born in “ << my_birthday.year(); 5

CSCE 121: Set 8: Classes Struct vs. Class For structs, the default access is public: any code component can read and write the data members and call the function members If we want to disallow that for some (or all) members, we need to explicitly label them as private A class is exactly the same as a struct, except the default access is private; to change this, we need to explicitly label the relevant members as public 6

CSCE 121: Set 8: Classes Date Class class Date { int y, d, m; public: int year() { return y; } void set_year(int yy) { y = yy; } // similarly for month and day };... Date my_birthday; my_birthday.set_year(1900); cout << “I was born in “ << my_birthday.year(); 7

CSCE 121: Set 8: Classes Organizing a Class Definition class X { public: // interface to users, accessible by all // functions // types // data (often best kept private) private: // implementation, accessible only by // members of this class // functions // types // data }; 8

CSCE 121: Set 8: Classes What Should be a Class? A class (or struct) represents an entity in your problem domain or in your solution Examples: vector, matrix, input stream, string, device driver, robot arm, picture on screen, dialog box, temperature reading,… Concept was originally introduced in the Simula67 programming language 9

CSCE 121: Set 8: Classes Why Bother with Private? Provide a clean interface – messy data and functions can be hidden Maintain an invariant – only a controlled set of functions can access the data Ease debugging – only a fixed set of functions can access the data Allow change of representation – only need to change a fixed set of functions – calling code can be oblivious 10

CSCE 121: Set 8: Classes Initializing a Class Object For the Date class so far, the user needs to – declare a Date object – separately set the year, month and day – it’s up to the user to do this sensibly A better way is to use a constructor: special member function of the class that creates and initializes an object of the class – simpler for the user of the class – can check whether initialization data is valid 11

CSCE 121: Set 8: Classes Validity Notion of a “valid Date” is an important special case of the idea of a valid value Try to design types so that values are guaranteed to be valid – make sure initially they are valid – make sure every update keeps them valid A rule for what constitutes a valid value is called an invariant – invariant for Date is unusually hard (leap years, etc.) 12

CSCE 121: Set 8: Classes Defining Constructors The constructor for a class is a function member with special syntax: – no return type, not even void – name is the same as the name of the class – can have parameters – after the parameter list, can initialize the data members “directly” (before the body and using a colon) Example: Date(int yy, int mm, int dd) : y(yy), m(mm), d(dd) { /* code to check for validity of yy-mm-dd */ } 13

CSCE 121: Set 8: Classes Calling Constructors A constructor is never explicitly called in your code Instead, a constructor is called automatically whenever you declare an object of that type If you do not include a constructor in your class, the system will make a “default constructor” with no arguments, which is called when you declare an object of that type But if you include a constructor in your class, then the default constructor is not made 14

CSCE 121: Set 8: Classes Multiple Constructors You can have more than one constructor in your class, as long as they differ in their argument list (number and/or types) When you create an object of that type, you must supply arguments that are appropriate for at least one constructor So after including the Date constructor on earlier slide: Date my_birthday; // doesn’t work anymore! Date my_birthday(1800,3,5); // works 15

CSCE 121: Set 8: Classes Defining Function Members Outside the Class A common style is to include only declarations of member functions inside the actual class definition and put the definitions of the member functions later. This can be done, but now the function names need to be marked with namespace syntax :: class Date { public: Date(int yy, int mm, int dd); // no body … }; Date::Date(int yy, int mm, int dd) : y(yy), m(mm), d(dd) { /* … */ }; 16

CSCE 121: Set 8: Classes Why Define Function Members Outside their Class Declaration? Keeps the declaration of the class smaller and easier for human reader to find all the members In large programs made up of multiple files, reduces the situations in which pieces must be recompiled (see p. 316) 17

CSCE 121: Set 8: Classes Throwing an Exception in a Constructor 18 class Date { public: class Invalid {}; // to be used as exception Date(int y, int m, int d); // check for valid date and initialize // … private: int y, m, d; // year, month, day bool check(int y, int m, int d); // is (y,m,d) a valid date? // (Why private?) }; bool Date::check(int y, int m, int d) { /* … */ } Date::Date(int yy, int mm, int dd) : y(yy), m(mm), d(dd) { if (!check(y,m,d)) throw Invalid(); }

CSCE 121: Set 8: Classes Simple Enumerations User-defined type specifying a list of constants (basically, names for integers) Default is that the list starts with 0 and increments by 1 enum { red, green }; // red = 0, green = 1 int color = red; Can change the default values: enum {good = 1, fail, bad = 4, eof = 8 } // fail = 2 Benefit: –red and green are more mnemonic than 0 and 1 Pitfalls: – cannot reuse the names red and green in this scope – nothing prevents you from assigning to color 19

CSCE 121: Set 8: Classes Enumeration Type You can give the enumeration a name and declare variables of that type enum Month {jan=1,feb,mar, /*…*/}; Month m1; Benefit is that now out-of-range values cannot be assigned to such a variable – in fact, only members of the enumeration can be assigned to it m1 = mar; // OK m1 = -14; // won’t compile m1 = 3; // won’t compile 20

CSCE 121: Set 8: Classes Enumeration Class (Scoped) To avoid name clashes with enumerations, define enumeration like this: enum class Month { jan = 1, feb, /* … */ }; Now you need to refer to jan as Month::jan But prevents unexpected clashes (such as dec (December) in Month and dec (decimal) in iostream New in C++11 We’ll assume this as we develop Date further 21

CSCE 121: Set 8: Classes Date Class With Month Enum Class 22 enum class Month {jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}; class Date { public: Date(int y, Month m, int d); // note type of middle argument // … private: int y; Month m; // note type int d; }; // … Date my_birthday(1900,8,Month::dec); // type error! Date my_birthday(1900,Month::dec,8); // OK

CSCE 121: Set 8: Classes Const Member Functions Remember that you can declare a variable as const or constexpr (cannot be changed) How can we ensure that a member function does not change a const object of the class? By marking the function with keyword const after its parameter list A const member function cannot modify any data members and cannot call any non- const member function Only const member functions can be called on a const object 23

CSCE 121: Set 8: Classes Const Member Functions Example class Date { int y, m, d; public: Date(int yy, int mm, int dd) : y(yy), m(mm), d(dd) {} int year() { return y; } int c_year() const { return y; } void set_year(int yy) { y = yy; } void c_set_year(int yy) const { y = yy; } // error }; int main() { Date d(1800,3,3); const Date cd(1900,4,4); cout << d.year(); cout << d.c_year(); cout << cd.year(); // error cout << cd.c_year(); d.set_year(2000); cd.set_year(3000); // error return 0; } 24

CSCE 121: Set 8: Classes Choosing Class Interface Minimal Complete Type-safe – Beware of confusing argument orders Const correct – Mark all function members as cons t if (and only if) they make no changes to data members 25

CSCE 121: Set 8: Classes Interfaces and Helper Functions Keep class interface (set of public functions) minimal – Simplifies understanding – Simplifies debugging – Simplifies maintenance But now we may need extra “helper functions” that are outside the class (non- member functions) 26

CSCE 121: Set 8: Classes Helper Functions Example Test for equality of two dates First cut: bool equals(Date d1, Date d2) { return (d1.year() == d2.year()) && (d1.month() == d2.month()) && (d1.day() == d2.day()); } //... Date my_birthday(1917,12,10); Date your_birthday(1917,12,10); if (equals(my_birthday,your_birthday))... 27

CSCE 121: Set 8: Classes Operator Overloading Wouldn’t it be nicer if we could compare two dates with ==? We can! In fact we can define almost all C++ built-in operators for class or enumeration operands – Called “operator overloading” Syntax is to define a function with the keyword operator followed by the symbol – Give the function the appropriate return type and formal arguments 28

CSCE 121: Set 8: Classes Operator Overloading Example bool operator==(const Date& a, const Date& b) { return (a.year() == b.year()) && (a.month() == b.month()) && (a.day() == b.day()); } bool operator!=(const Date& a, const Date& b) { return !(a==b); // take advantage of work already } // done 29

CSCE 121: Set 8: Classes Operator Overloading Rules You can define only existing operators + - * / % [] () ^ ! & >= etc. You can define operators only with their conventional number of operands – E.g., no unary < and no binary ! An overloaded operator must have at least one user-defined type as operand int operator+(int,int); // error 30

CSCE 121: Set 8: Classes Operator Overloading Advice Overload operators only with their conventional meaning + should be some kind of addition, etc. Don’t overload unless you have a good reason 31

CSCE 121: Set 8: Classes Essential Class Operations Constructor – Default constructor does nothing Copy constructor – Determines what should be done if you initialize a newly declared variable by assigning to it a pre-existing variable – Default copy constructor copies data members Copy assignment – Determines what should be done if you assign one pre-existing variable to another pre-existing variable – Default copy assignment copies data members Destructor – Determines what should be done if the variable goes out of scope – Default destructor does nothing 32

CSCE 121: Set 8: Classes Copy Constructor and Copy Assignment Examples Date d1(1800,1,1); Date d2 = d1; // copy constructor invoked Date d3(1900,2,2); d3 = d2; // copy assignment invoked 33

CSCE 121: Set 8: Classes Acknowledgments Photo on slide 1: by Tuomo Tamenpää, licensed under CC BY-NC-SA 2.0Tuomo TamenpääCC BY-NC-SA 2.0 Slides are based on those for the textbook: 34