Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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 and Jennifer Welch

2 CSCE 121:509-512 -- 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

3 CSCE 121:509-512 -- 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

4 CSCE 121:509-512 -- 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

5 CSCE 121:509-512 -- 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

6 CSCE 121:509-512 -- 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

7 CSCE 121:509-512 -- 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

8 CSCE 121:509-512 -- 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

9 CSCE 121:509-512 -- 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

10 CSCE 121:509-512 -- 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

11 CSCE 121:509-512 -- 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

12 CSCE 121:509-512 -- 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

13 CSCE 121:509-512 -- 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

14 CSCE 121:509-512 -- 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

15 CSCE 121:509-512 -- 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

16 CSCE 121:509-512 -- 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

17 CSCE 121:509-512 -- 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

18 CSCE 121:509-512 -- 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(); }

19 CSCE 121:509-512 -- 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 -4762 to color 19

20 CSCE 121:509-512 -- 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

21 CSCE 121:509-512 -- 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

22 CSCE 121:509-512 -- 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

23 CSCE 121:509-512 -- 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

24 CSCE 121:509-512 -- 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

25 CSCE 121:509-512 -- 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

26 CSCE 121:509-512 -- 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

27 CSCE 121:509-512 -- 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

28 CSCE 121:509-512 -- 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

29 CSCE 121:509-512 -- 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

30 CSCE 121:509-512 -- 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

31 CSCE 121:509-512 -- 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

32 CSCE 121:509-512 -- 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

33 CSCE 121:509-512 -- 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

34 CSCE 121:509-512 -- 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: http://www.stroustrup.com/Programming/9_classes.ppt 34


Download ppt "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."

Similar presentations


Ads by Google