Question? Leave a message!




Vectors, Enumeration, Overloading

Vectors, Enumeration, Overloading
CIS 190: C/C++ Programming Lecture 9 Vectors, Enumeration, Overloading, and More 1 Outline • Access Restriction • Vectors • Enumeration • Operator Overloading • New/Delete • Destructors • Homework Project 2 Principle of Least Privilege • what is it 3 Principle of Least Privilege • every module – process, user, program, etc. • must have access only to the information and resources – functions, variables, etc. • that are necessary for legitimate purposes – (i.e., this is why variables are private) 4 Access Specifiers for Date Class class Date public: void OutputMonth(); int GetMonth(); int GetDay(); int GetYear(); void SetMonth(int m); void SetDay (int d); void SetYear (int y); private: int mmonth; int mday; int myear; ; 5 Access Specifiers for Date Class class Date public: void OutputMonth(); int GetMonth(); int GetDay(); int GetYear(); should all of these void SetMonth(int m); functions really be void SetDay (int d); publicly accessible void SetYear (int y); private: int mmonth; int mday; int myear; ; 6 Outline • Access Restriction • Vectors • Enumeration • Operator Overloading • New/Delete • Destructors • Homework Project 7 Vectors • similar to arrays, but much more flexible – C++ will handle most of the “annoying” bits • provided by the C++ Standard Template Library (STL) – must include vector to use 8 Declaring a Vector vector int intA; – empty integer vector, called intA intA 9 Declaring a Vector vector int intB (10); – integer vector with 10 integers, initialized (by default) to zero 0 0 0 0 0 0 0 0 0 0 intB 10 Declaring a Vector vector int intC (10, 1); – integer vector with 10 integers, initialized to 1 1 1 1 1 1 1 1 1 1 1 intC 11 Vector Assignment • unlike arrays, can assign one vector to another – even if they’re different sizes – as long as they’re the same type intA = intB; 12 Vector Assignment • unlike arrays, can assign one vector to another – even if they’re different sizes – as long as they’re the same type intA = intB; size 0 size 10 (intA is now 10 elements too) 13 Vector Assignment • unlike arrays, can assign one vector to another – even if they’re different sizes – as long as they’re the same type intA = intB; size 0 size 10 (intA is now 10 elements too) 0 0 0 0 0 0 0 0 0 0 intA 14 Vector Assignment • unlike arrays, can assign one vector to another – even if they’re different sizes – as long as they’re the same type intA = intB; size 0 size 10 (intA is now 10 elements too) intA = charA; 15 Vector Assignment • unlike arrays, can assign one vector to another – even if they’re different sizes – as long as they’re the same type intA = intB; size 0 size 10 (intA is now 10 elements too) intA = charA; NOT okay 16 Copying Vectors • can create a copy of an existing vector when declaring a new vector vector int intD (intC); 1 1 1 1 1 1 1 1 1 1 intC 17 Copying Vectors • can create a copy of an existing vector when declaring a new vector vector int intD (intC); 1 1 1 1 1 1 1 1 1 1 intC 1 1 1 1 1 1 1 1 1 1 intD 18 Accessing Vector Members • we have two different methods available • square brackets: intB2 = 7; • .at() operation: intB.at(2) = 7; 19 Accessing Vector Members with • function just as they did with arrays in C for (i = 0; i 10; i++) intBi = i; 20 Accessing Vector Members with • function just as they did with arrays in C for (i = 0; i 10; i++) intBi = i; 0 1 2 3 4 5 6 7 8 9 intB 21 Accessing Vector Members with • function just as they did with arrays in C for (i = 0; i 10; i++) intBi = i; 0 1 2 3 4 5 6 7 8 9 intB • but there is still no bounds checking – going out of bounds may cause segfaults 22 Accessing Vector Members with .at() • the.at() operator uses bounds checking • will throw an exception when out of bounds – causes program to terminate – we can handle it (with trycatch blocks) • we’ll cover these later in the semester • slower than , but much safer 23 Passing Vectors to Functions • unlike arrays, vectors are by default passed by value to functions – a copy is made, and that copy is passed to the function – changes made do not show in main() • but we can explicitly pass vectors by reference 24 Passing Vectors by Reference • to pass vectors by reference, nothing changes in the function call: // function call: // good for passing by value // and for passing by reference ModifyV (refVector); • which is really handy (but can also cause confusion about what’s going on, so be careful) 25 Passing Vectors by Reference • but to pass a vector by reference, we do need to change the function prototype: // function prototype // for passing by value void ModifyV (vector int ref); • what do you think needs to change 26 Passing Vectors by Reference • but to pass a vector by reference, we do need to change the function prototype: void ModifyV (vector int ref); void ModifyV (vector int ref); void ModifyV (vector int ref); void ModifyV (vector int ref); void ModifyV (vectorint ref); • what do you think needs to change 27 Passing Vectors by Reference • but to pass a vector by reference, we do need to change the function prototype: void ModifyV (vector int ref); 28 MultiDimensional Vectors • 2dimensional vectors are essentially “a vector of vectors” vector vector char charVec; 29 MultiDimensional Vectors • 2dimensional vectors are essentially “a vector of vectors” vector vector char charVec; this space in between the two closing ‘’ characters is required by many implementations of C++ 30 Accessing Elements in 2D Vectors • to access 2D vectors, just chain accessors: • square brackets: intB23 = 7; • .at() operator: intB.at(2).at(3) = 7; 31 Accessing Elements in 2D Vectors • to access 2D vectors, just chain accessors: you should be using • square brackets: the .at() operator intB23 = 7; though, since it is much safer than • .at() operator: intB.at(2).at(3) = 7; 32 resize() void resize (n, val); 33 resize() void resize (n, val); • n is the new size of the vector – if larger than current • vector size is expanded – if smaller than current • vector is reduced to first n elements 34 resize() void resize (n, val); • val is an optional value – used to initialize any new elements • if not given, the default constructor is used 35 Using resize() • if we declare an empty vector, one way we can change it to the size we want is resize() vector string stringVec; stringVec.resize(9); 36 Using resize() • if we declare an empty vector, one way we can change it to the size we want is resize() vector string stringVec; stringVec.resize(9); – or, if we want to initialize the new elements: stringVec.resize(9, “hello”); 37 pushback() • add a new element at the end of a vector void pushback (val); 38 pushback() • add a new element at the end of a vector void pushback (val); • val is the value of the new element that will be added to the end of the vector charVec.pushback(‘a’); 39 resize() vs pushback() • resize() is best used when you know the exact size a vector needs to be • pushback() is best used when elements are added one by one 40 resize() vs pushback() • resize() is best used when you know the exact size a vector needs to be – like when you have the exact number of songs a singer has in their repertoire • pushback() is best used when elements are added one by one 41 resize() vs pushback() • resize() is best used when you know the exact size a vector needs to be – like when you have the exact number of songs a singer has in their repertoire • pushback() is best used when elements are added one by one – like when you are getting train cars from a user 42 size() • unlike arrays, vectors in C++ “know” their size – due to C++ managing vectors for you • size() returns the number of elements in the vector it is called on – does not return an integer – you will need to cast it 43 Using size() int cSize; // this will not work cSize = charVec.size(); 44 Using size() int cSize; // this will not work cSize = charVec.size(); //you must cast the return type cSize = (int) charVec.size(); 45 Livecoding • let’s apply what we’ve learned about vectors • declaration of multidimensional vectors • .at() operator • resize(), pushback() • size() LIVECODING LIVECODING 46 Outline • Access Restriction • Vectors • Enumeration • Operator Overloading • New/Delete • Destructors • Homework Project 47 Enumeration • enumerations are a type of variable used to set up collections of named integer constants • useful for “lists” of values that are tedious to implement using define or const define WINTER 0 define SPRING 1 define SUMMER 2 define FALL 3 48 Enumeration Types • two types of enum declarations: • named type enum seasons WINTER, SPRING, SUMMER, FALL; • unnamed type enum WINTER, SPRING, SUMMER, FALL; 49 Named Enumerations • named types allow you to create variables of that type, use it in function arguments, etc. // declare a variable of // the enumeration type seasons // called currentSemester enum seasons currentSemester; currentSemester = FALL; 50 Unnamed Enumerations • unnamed types are useful for naming constants that won’t be used as variables 51 Unnamed Enumerations • unnamed types are useful for naming constants that won’t be used as variables int userChoice; cout “Please enter season: ”; cin userChoice; switch(userChoice) case WINTER: cout “brr”; / etc / 52 Benefits of Enumeration • named enumeration types allow you to restrict assignments to only valid values – a ‘seasons’ variable cannot have a value other than those in the enum declaration • unnamed types allow simpler management of a large list of constants, but don’t prevent invalid values from being used 53 Outline • Access Restriction • Vectors • Enumeration • Operator Overloading • New/Delete • Destructors • Homework Project 54 Function Overloading • last class, covered overloading constructors: • and overloading other functions: void PrintMessage (void); void PrintMessage (string msg); 55 Operators • given variable types have predefined behavior for operators like +, , ==, and more • for example: stringP = stringQ; if (charX == charY) intA = intB + intC; intD += intE; 56 Operators • would be nice to have these operators also work for userdefined variables, like classes • we could even have them as member functions – allows access to member variables and functions that are set to private • this is all possible via operator overloading 57 Overloading Restrictions • cannot overload ::, . , , or : • cannot create new operators • overloadable operators include =, , , ++, , +=, +, , , =, =, ==, =, 58 Why Overload • let’s say we have a Money class: class Money public: / etc / private: int mdollars; int mcents; ; 59 Why Overload • and we have two Money objects: Money cash(700, 65); Money bills(99, 85); 60 Why Overload • and we have two Money objects: // we have 700.65 in cash, and // need to pay 99.85 for bills Money cash(700, 65); Money bills(99, 85); 61 Why Overload • and we have two Money objects: // we have 700.65 in cash, and // need to pay 99.85 for bills Money cash(700, 65); Money bills(99, 85); • what happens if we do the following cash = cash bills; 62 Why Overload • and we have two Money objects: // we have 700.65 in cash, and // need to pay 99.85 for bills cash is now 601 Money cash(700, 65); dollars and 20 Money bills(99, 85); cents, or 601.20 • what happens if we do the following cash = cash bills; 63 Why Overload • that doesn’t make any sense • what’s going on 64 Why Overload • the default subtraction operator provided by the compiler only works on a naïve level – subtracts bills.mdollars from cash.mdollars – and subtracts bills.mcents from cash.mcents 65 Why Overload • the default subtraction operator provided by the compiler only works on a naïve level – subtracts bills.mdollars from cash.mdollars – and subtracts bills.mcents from cash.mcents • this isn’t what we want – so we must write our own subtraction operator 66 Operator Overloading Prototype Money operator (const Money amount2); 67 Operator Overloading Prototype Money operator (const Money amount2); we’re returning an object of the class type 68 Operator Overloading Prototype Money operator (const Money amount2); this tells the compiler that we are overloading an operator we’re returning an object of the class type 69 Operator Overloading Prototype Money operator (const Money amount2); this tells the compiler that we are overloading an operator we’re returning and that it’s an object of the subtraction the class type operator 70 Operator Overloading Prototype Money operator (const Money amount2); this tells the we’re passing in a compiler that Money object we are overloading an operator we’re returning and that it’s an object of the subtraction the class type operator 71 Operator Overloading Prototype Money operator (const Money amount2); this tells the we’re passing in a compiler that Money object as a we are const overloading an operator we’re returning and that it’s an object of the subtraction the class type operator 72 Operator Overloading Prototype Money operator (const Money amount2); this tells the we’re passing in a compiler that Money object as a we are const and by overloading reference an operator we’re returning and that it’s an object of the subtraction the class type operator 73 Operator Overloading Prototype Money operator (const Money amount2); this tells the we’re passing in a compiler that Money object as a we are const and by overloading reference an operator why would we want to do that we’re returning and that it’s an object of the subtraction the class type operator 74 Operator Overloading Definition Money operator (const Money amount2) int dollarsRet, centsRet; int total, minusTotal; // how would you solve this return Money(dollarsRet, centsRet); 75 When to Overload Operators • do the following make sense as operators (1) today = today + tomorrow; (2) if (today == tomorrow) 76 When to Overload Operators • do the following make sense as operators (1) today = today + tomorrow; (2) if (today == tomorrow) • only overload an operator for a class that “makes sense” for that class – otherwise it can be confusing to the programmer • use your best judgment 77 Outline • Access Restriction • Vectors • Enumeration • Operator Overloading • New/Delete • Destructors • Homework Project 78 new and delete • replace malloc() and free() from C – keywords instead of functions • don’t need them for vectors – vectors can change size dynamically • mostly used for – dynamic data structures (linked list, trees, etc.) – pointers 79 Using new and delete Date datePtr1, datePtr2; datePtr1 = new Date; datePtr2 = new Date(7,4); delete datePtr1; delete datePtr2; 80 Managing Memory in C++ • just as important as managing memory in C • just because new and delete are easier to use than malloc and free, doesn’t mean they can’t be prone to the same errors – “losing” pointers – memory leaks – when memory should be deleted (freed) 81 Outline • Access Restriction • Vectors • Enumeration • Operator Overloading • New/Delete • Destructors • Homework Project 82 Refresher on Constructors • special member functions used to create (or “construct”) new objects • automatically called when an object is created – implicit: Money cash; – explicit: Money bills (89, 40); • initializes the values of all data members 83 Destructors • destructors are the opposite of constructors • they are used when delete() is called on an instance of a usercreated class • compiler automatically provides one for you – but it does not take into account dynamic memory 84 Destructor Example • let’s say we have a new member variable of our Date class called ‘mnextholiday’ – pointer to a string with the name of the next holiday class Date private: int mmonth; int mday; int myear; string mnextholiday ; ; 85 Destructor Example • we will need to update the constructor Date::Date (int m, int d, int y, string nextholiday) SetMonth(m); SetDay(d); SetYear(y); mnextholiday = new string; mnextholiday = nextholiday; 86 Destructor Example • we will need to update the constructor what other changes do Date::Date (int m, int d, int y, string nextholiday) we need to make to a SetMonth(m); class when adding a new member variable SetDay(d); SetYear(y); mnextholiday = new string; mnextholiday = nextholiday; 87 Destructor Example • we also now need to create a destructor of our own: Date(); // our destructor • destructors must have a tilde in front • like a constructor: – it has no return type – same name as the class 88 Basic Destructor Definition • the destructor needs to free any dynamically allocated memory • most basic version of a destructor Date::Date() delete mnextholiday; 89 Ideal Destructor Definition • clears all information and sets pointers to NULL Date::Date() // clear member variable info mday = mmonth = myear = 0; mnextholiday = “”; // free and set pointers to NULL delete mnextholiday; mnextholiday = NULL; 90 Ideal Destructor Definition why aren’t we • clears all information and sets pointers to NULL using the mutator functions here Date::Date() // clear member variable info mday = mmonth = myear = 0; mnextholiday = “”; // free and set pointers to NULL delete mnextholiday; mnextholiday = NULL; 91 Outline • Access Restriction • Vectors • Enumeration • Operator Overloading • New/Delete • Destructors • Homework Project 92 Homework 6 • Classy Trains – last homework • practice with implementing a C++ class • more emphasis on: – error checking – code style and choices 93 Project • final project will be due December 2nd – two presentation days: – December 2nd, 67:30 PM, Towne 100 (Tue) – December 3rd, 1:303 PM, Towne 319 (Wed) • you can’t use late days for project deadlines • details will be up before next class 94 Project • project must be completed in groups (of two) th – groups will be due October 29 on Piazza – if you don’t have a group, you’ll be assigned one • start thinking about: – who you want to work with – what sort of project you want to do – what you want to name your group 95
sharer
Presentations
Free
Document Information
Category:
Presentations
User Name:
Dr.MasonHanks
User Type:
Teacher
Country:
Germany
Uploaded Date:
23-07-2017