├── Chapter01 ├── Assessments │ ├── Chp1-Q3.cpp │ └── ReadMeChp1.pdf ├── Chp1-Ex1.cpp ├── Chp1-Ex10.cpp ├── Chp1-Ex11.cpp ├── Chp1-Ex2.cpp ├── Chp1-Ex3.cpp ├── Chp1-Ex4.cpp ├── Chp1-Ex5.cpp ├── Chp1-Ex6.cpp ├── Chp1-Ex7.cpp ├── Chp1-Ex8.cpp ├── Chp1-Ex9.cpp ├── ReadMe └── original │ ├── Chp1-Ex1.cpp │ ├── Chp1-Ex10.cpp │ ├── Chp1-Ex11.cpp │ ├── Chp1-Ex2.cpp │ ├── Chp1-Ex3.cpp │ ├── Chp1-Ex4.cpp │ ├── Chp1-Ex5.cpp │ ├── Chp1-Ex6.cpp │ ├── Chp1-Ex7.cpp │ ├── Chp1-Ex8.cpp │ ├── Chp1-Ex9.cpp │ └── ReadMe ├── Chapter02 ├── Assessments │ ├── Chp2-Q2.cpp │ └── ReadMeChp2.pdf ├── Chp2-Ex1.cpp ├── Chp2-Ex2.cpp ├── Chp2-Ex3.cpp ├── Chp2-Ex4.cpp ├── Chp2-Ex5.cpp ├── Chp2-Ex6.cpp ├── Chp2-Ex7.cpp ├── Chp2-Ex8.cpp ├── ReadMe └── original │ ├── Chp2-Ex1.cpp │ ├── Chp2-Ex2.cpp │ ├── Chp2-Ex3.cpp │ ├── Chp2-Ex4.cpp │ ├── Chp2-Ex5.cpp │ ├── Chp2-Ex6.cpp │ ├── Chp2-Ex7.cpp │ ├── Chp2-Ex8.cpp │ └── ReadMe ├── Chapter03 ├── Assessments │ ├── Chp3-Q1.cpp │ ├── Chp3-Q2.cpp │ └── ReadMeChp3.pdf ├── Chp3-Ex1.cpp ├── Chp3-Ex2.cpp ├── Chp3-Ex3.cpp ├── Chp3-Ex4.cpp ├── Chp3-Ex5.cpp ├── Chp3-Ex6.cpp ├── Chp3-Ex7.cpp ├── Chp3-Ex8.cpp ├── Chp3-Ex9.cpp ├── ReadMe └── original │ ├── Chp3-Ex1.cpp │ ├── Chp3-Ex2.cpp │ ├── Chp3-Ex3.cpp │ ├── Chp3-Ex4.cpp │ ├── Chp3-Ex5.cpp │ ├── Chp3-Ex6.cpp │ ├── Chp3-Ex7.cpp │ ├── Chp3-Ex8.cpp │ ├── Chp3-Ex9.cpp │ └── ReadMe ├── Chapter04 ├── Assessments │ ├── Chp4-Q1.cpp │ └── ReadMeChp4.pdf ├── Chp4-Ex1.cpp ├── Chp4-Ex2.cpp ├── Chp4-Ex3.cpp ├── Chp4-Ex4.cpp ├── Chp4-Ex5.cpp ├── Chp4-Ex6.cpp ├── Chp4-Ex7.cpp ├── ReadMe └── original │ ├── Chp4-Ex1.cpp │ ├── Chp4-Ex2.cpp │ ├── Chp4-Ex3.cpp │ ├── Chp4-Ex4.cpp │ ├── Chp4-Ex5.cpp │ ├── Chp4-Ex6.cpp │ ├── Chp4-Ex7.cpp │ └── ReadMe ├── Chapter05 ├── Assessments │ ├── Chp5-Q1.cpp │ └── ReadMeChp5.pdf ├── Chp5-Ex1.cpp ├── Chp5-Ex10.cpp ├── Chp5-Ex11.cpp ├── Chp5-Ex2.cpp ├── Chp5-Ex3.cpp ├── Chp5-Ex4.cpp ├── Chp5-Ex5.cpp ├── Chp5-Ex6.cpp ├── Chp5-Ex7.cpp ├── Chp5-Ex8.cpp ├── Chp5-Ex9.cpp ├── ReadMe └── original │ ├── Chp5-Ex1.cpp │ ├── Chp5-Ex10.cpp │ ├── Chp5-Ex11.cpp │ ├── Chp5-Ex2.cpp │ ├── Chp5-Ex3.cpp │ ├── Chp5-Ex4.cpp │ ├── Chp5-Ex5.cpp │ ├── Chp5-Ex6.cpp │ ├── Chp5-Ex7.cpp │ ├── Chp5-Ex8.cpp │ ├── Chp5-Ex9.cpp │ └── ReadMe ├── Chapter06 ├── Assessments │ ├── Chp6-Q1.cpp │ └── ReadMeChp6.pdf ├── Chp6-Ex1.cpp ├── Chp6-Ex2.cpp ├── Chp6-Ex3.cpp ├── Chp6-Ex4.cpp ├── ReadMe └── original │ ├── Chp6-Ex1.cpp │ ├── Chp6-Ex2.cpp │ ├── Chp6-Ex3.cpp │ ├── Chp6-Ex4.cpp │ └── ReadMe ├── Chapter07 ├── Assessments │ ├── Chp7-Q1.cpp │ └── ReadMeChp7.pdf ├── Chp7-Ex1.cpp ├── ReadMe └── original │ ├── Chp7-Ex1.cpp │ └── ReadMe ├── Chapter08 ├── Assessments │ ├── Chp8-Q1.cpp │ └── ReadMeChp8.pdf ├── Chp8-Ex1.cpp ├── ReadMe └── original │ ├── Chp8-Ex1.cpp │ └── ReadMe ├── Chapter09 ├── Assessments │ ├── ReadMeChp9.pdf │ ├── chp9-Q1.cpp │ └── chp9-Q2.cpp ├── Chp9-Ex1.cpp ├── Chp9-Ex2.cpp ├── Chp9-Ex3.cpp ├── ReadMe └── original │ ├── Chp9-Ex1.cpp │ ├── Chp9-Ex2.cpp │ ├── Chp9-Ex3.cpp │ └── ReadMe ├── Chapter10 ├── Assessments │ └── ReadMeChp10.pdf ├── Chp10-Ex1.cpp ├── Chp10-Ex2.cpp ├── ReadMe └── original │ ├── Chp10-Ex1.cpp │ ├── Chp10-Ex2.cpp │ └── ReadMe ├── Chapter11 ├── Assessments │ └── ReadMeChp11.pdf ├── Chp11-Ex1.cpp ├── Chp11-Ex2.cpp ├── Chp11-Ex3.cpp ├── Chp11-Ex4.cpp ├── Chp11-Ex5.cpp ├── Chp11-Ex6.cpp ├── ReadMe └── original │ ├── Chp11-Ex1.cpp │ ├── Chp11-Ex2.cpp │ ├── Chp11-Ex3.cpp │ ├── Chp11-Ex4.cpp │ ├── Chp11-Ex5.cpp │ ├── Chp11-Ex6.cpp │ └── ReadMe ├── Chapter12 ├── Assessments │ └── ReadMeChp12.pdf ├── Chp12-Ex1.cpp ├── Chp12-Ex2.cpp ├── Chp12-Ex3.cpp ├── ReadMe └── original │ ├── Chp12-Ex1.cpp │ ├── Chp12-Ex2.cpp │ ├── Chp12-Ex3.cpp │ └── ReadMe ├── Chapter13 ├── Assessments │ └── ReadMeChp13.pdf ├── Chp13-Ex1.cpp ├── Chp13-Ex2.cpp ├── Chp13-Ex3.cpp ├── ReadMe └── original │ ├── Chp13-Ex1.cpp │ ├── Chp13-Ex2.cpp │ ├── Chp13-Ex3.cpp │ └── ReadMe ├── Chapter14 ├── Assessments │ └── ReadMeChp14.pdf ├── Chp14-Ex1.cpp ├── Chp14-Ex2.cpp ├── Chp14-Ex3.cpp ├── Chp14-Ex4.cpp ├── Chp14-Ex5.cpp ├── Chp14-Ex6.cpp ├── Chp14-Ex7.cpp ├── Chp14-Ex8.cpp ├── ReadMe └── original │ ├── Chp14-Ex1.cpp │ ├── Chp14-Ex2.cpp │ ├── Chp14-Ex3.cpp │ ├── Chp14-Ex4.cpp │ ├── Chp14-Ex5.cpp │ ├── Chp14-Ex6.cpp │ ├── Chp14-Ex7.cpp │ ├── Chp14-Ex8.cpp │ └── ReadMe ├── Chapter15 ├── Assessments │ └── ReadMeChp15.pdf ├── Chp15-Ex1.cpp ├── Chp15-Ex2.cpp ├── Person.cpp ├── Person.h ├── ReadMe ├── Student.cpp ├── Student.h └── original │ ├── Chp15-Ex1.cpp │ ├── Chp15-Ex2.cpp │ ├── Person.cpp │ ├── Person.h │ ├── ReadMe │ ├── Student.cpp │ └── Student.h ├── Chapter16 ├── Assessments │ └── ReadMeChp16.pdf ├── Chp16-Ex1.cpp ├── ReadMe └── original │ ├── Chp16-Ex1.cpp │ └── ReadMe ├── Chapter17 ├── Assessments │ └── ReadMeChp17.pdf ├── Chp17-Ex1.cpp ├── Chp17-Ex2.cpp ├── ReadMe └── original │ ├── Chp17-Ex1.cpp │ ├── Chp17-Ex2.cpp │ └── ReadMe ├── Chapter18 ├── Assessments │ └── ReadMeChp18.pdf ├── Chp18-Ex1.cpp ├── Chp18-Ex2.cpp ├── Chp18-Ex3.cpp ├── ReadMe └── original │ ├── Chp18-Ex1.cpp │ ├── Chp18-Ex2.cpp │ ├── Chp18-Ex3.cpp │ └── ReadMe ├── Chapter19 ├── Assesssments │ └── ReadMeChp19.pdf ├── Chp19-Ex1.cpp ├── Chp19-Ex1b.cpp ├── Chp19-Ex2.cpp ├── Chp19-Ex3.cpp ├── ReadMe └── original │ ├── Chp19-Ex1.cpp │ ├── Chp19-Ex2.cpp │ ├── Chp19-Ex3.cpp │ └── ReadMe ├── Chapter20 ├── Assessments │ └── ReadMeChp20.pdf ├── Chp20-Ex1.cpp ├── Chp20-Ex2.cpp ├── Person.h ├── PersonImpl.cpp ├── ReadMe ├── original │ ├── Chp20-Ex1.cpp │ ├── Chp20-Ex2.cpp │ ├── Person.h │ ├── PersonImpl.cpp │ ├── ReadMe │ └── unique │ │ ├── Chp20-Ex3.cpp │ │ ├── Person.h │ │ ├── PersonImpl.cpp │ │ └── ReadMe └── unique │ ├── Chp20-Ex3.cpp │ ├── Person.h │ ├── PersonImpl.cpp │ └── ReadMe ├── Chapter21 ├── Chp21-Ex1.cpp ├── Chp21-Ex2.cpp ├── Chp21-Ex3.cpp ├── Chp21-Ex4.cpp ├── Chp21-Ex5.cpp ├── Chp21-Ex6.cpp ├── Person.cpp ├── Person.h └── ReadMe ├── LICENSE └── README.md /Chapter01/Assessments/Chp1-Q3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Chapter 1, Question 3 -- Sample Solution 3 | 4 | // Create a simple program using a struct or a class to make a user defined type 5 | // for Book. Add data members for title, author, and number of pages. Create two 6 | // variables of type Book and use the dot operator . to fill in the data members 7 | // for each such instance. Use iostreams to both prompt the user for input values, and 8 | // to print each Book instance when complete. Use only features covered in this chapter. 9 | 10 | #include 11 | 12 | using std::cout; // preferred to: using namespace std; 13 | using std::cin; 14 | using std::endl; 15 | using std::string; 16 | 17 | class Book 18 | { 19 | public: 20 | string title; 21 | string author; 22 | int numPages; 23 | }; 24 | 25 | int main() 26 | { 27 | Book b1; 28 | cout << "Please enter book title : "; 29 | cin >> b1.title; 30 | cout << "Please enter book author : "; 31 | cin >> b1.author; 32 | cout << "Please enter book number of pages: "; 33 | cin >> b1.numPages; 34 | cout << b1.title << " with author: " << b1.author << " with page count: " << b1.numPages << endl; 35 | 36 | Book b2; 37 | cout << "Please enter book title : "; 38 | cin >> b2.title; 39 | cout << "Please enter book author : "; 40 | cin >> b2.author; 41 | cout << "Please enter book number of pages: "; 42 | cin >> b2.numPages; 43 | cout << b2.title << " with author: " << b2.author << " with page count: " << b2.numPages << endl; 44 | return 0; 45 | } 46 | 47 | 48 | -------------------------------------------------------------------------------- /Chapter01/Assessments/ReadMeChp1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter01/Assessments/ReadMeChp1.pdf -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate very simple I/O with iostreams 3 | // Don't worry -- we'll add safety measures in the very next example (see comment below) 4 | 5 | #include 6 | 7 | using std::cin; // preferred to: using namespace std; 8 | using std::cout; 9 | using std::endl; 10 | 11 | int main() 12 | { 13 | char name[20]; // caution, uninitialized array of char 14 | int age = 0; 15 | cout << "Please enter a name and an age: "; 16 | // we'll see in the next example how to ensure we don't overflow the name buffer 17 | cin >> name >> age; 18 | cout << "Hello " << name; 19 | cout << ". You are " << age << " years old." << endl; 20 | return 0; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex10.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple enum types 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | using std::string; 9 | 10 | enum day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; 11 | 12 | enum workDay {Mon = 1, Tues, Wed, Thurs, Fri}; 13 | 14 | // strongly typed enums default to int, but can be any integral type: int, char, short int, long int, bool 15 | 16 | enum struct WinterHoliday { Diwali, Hanukkah, ThreeKings, WinterSolstice, StLucia, StNicholas, Christmas, Kwanzaa }; 17 | 18 | enum class Holiday : short int { NewYear = 1, MLK, Memorial, Independence, Labor, Thanksgiving }; 19 | 20 | int main() 21 | { 22 | day birthday = Monday; 23 | workDay payday = Fri; 24 | 25 | WinterHoliday myTradition = WinterHoliday::StNicholas; 26 | Holiday favorite = Holiday::NewYear; 27 | 28 | cout << "Birthday is " << birthday << endl; 29 | cout << "Payday is " << payday << endl; 30 | 31 | cout << "Traditional Winter holiday is " << static_cast (myTradition) << endl; 32 | cout << "Favorite holiday is " << static_cast (favorite) << endl; 33 | 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex11.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review namespaces (adding new and augmenting existing namespaces) 3 | // This example explores ambiguities of opening multiple namespaces with duplicative elements 4 | 5 | #include 6 | 7 | // using namespace std; // This statement brings in entire namespace std 8 | using std::cout; // Instead, we can bring in individual elements.... 9 | using std::endl; // See book discussion as to why this is preferred. 10 | 11 | namespace DataTypes 12 | { 13 | int total; 14 | 15 | class LinkList 16 | { // full class definition ... 17 | }; 18 | 19 | class Stack 20 | { // full class definition ... 21 | }; 22 | }; 23 | 24 | namespace AbstractDataTypes 25 | { 26 | class Stack 27 | { // full class definition ... 28 | }; 29 | 30 | class Queue 31 | { // full class definition ... 32 | }; 33 | }; 34 | 35 | namespace AbstractDataTypes 36 | { 37 | int total; 38 | 39 | class Tree 40 | { // full class definition ... 41 | }; 42 | }; 43 | 44 | 45 | int main() 46 | { 47 | 48 | using namespace AbstractDataTypes; // activate namespace 49 | using DataTypes::LinkList; // activate only LinkList 50 | 51 | LinkList list1; // LinkList is found in DataTypes 52 | Stack stack1; // Stack is found in AbstractDataTypes 53 | 54 | total = 5; // from active AbstractDataTypes 55 | DataTypes::total = 85; // specify non-active member 56 | 57 | cout << "total " << total << "\n"; 58 | cout << "DataTypes::total " << DataTypes::total << endl; 59 | 60 | return 0; 61 | } 62 | 63 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To illustrate basic iostream manipulators 3 | 4 | #include 5 | #include 6 | 7 | using std::cout; // preferred to: using namespace std; 8 | using std::cin; 9 | using std::endl; 10 | using std::flush; 11 | using std::setw; 12 | using std::setprecision; 13 | 14 | int main() 15 | { 16 | char name[20]; // caution; unitialized array of char 17 | float gpa = 0.0; 18 | cout << "Please enter a name and a gpa: "; 19 | // Now, we won't overflow the input buffer of name (by using setw) 20 | cin >> setw(20) >> name >> gpa; 21 | cout << "Hello " << name << flush; 22 | cout << ". GPA is: " << setprecision(3) << gpa << endl; 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To review conditional statements 3 | 4 | #include 5 | 6 | using std::cin; // preferred to: using namespace std; 7 | using std::cout; 8 | using std::endl; 9 | 10 | int main() 11 | { 12 | int x = 0; 13 | 14 | cout << "Enter an integer: "; 15 | cin >> x; 16 | 17 | if (x == 0) 18 | cout << "x is 0" << endl; 19 | else if (x < 0) 20 | cout << "x is negative" << endl; 21 | else 22 | { 23 | cout << "x is positive" << endl; 24 | cout << "and ten times x is: " << x*10 << endl; 25 | } 26 | 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To review simple looping with while and do-while 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | int main() 10 | { 11 | int i = 0; 12 | 13 | while (i < 10) 14 | { 15 | cout << i << endl; 16 | i++; 17 | } 18 | 19 | i = 0; 20 | 21 | do 22 | { 23 | cout << i << endl; 24 | i++; 25 | } while (i < 10); 26 | 27 | 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple looping with for loops 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | int main() 10 | { 11 | int i; // though we'll prefer to declare i within the loop to limit its scope to the loop only 12 | // (and will do so ever after), this example is paired with the book to discuss the scope of 13 | // i when it is declared outside of the loop as a cautionary warning. 14 | // It is compared to j's scope below. 15 | 16 | for (i = 0; i < 10; i++) 17 | cout << i << endl; 18 | 19 | for (int j = 0; j < 10; j++) // preferred declaration of loop control variable within loop 20 | cout << j << endl; 21 | 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex6.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review nested for loops 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | int main() 10 | { 11 | for (int i = 0; i < 10; i++) // Notice our preferred declaration of i within the loop construct 12 | { 13 | cout << i << endl; 14 | 15 | for (int j = 0; j < 10; j++) 16 | cout << j << endl; 17 | 18 | cout << "\n"; 19 | } 20 | 21 | 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review a simple function 3 | 4 | #include 5 | 6 | using std::cin; // preferred to: using namespace std; 7 | using std::cout; 8 | using std::endl; 9 | 10 | int Minimum (int a, int b) 11 | { 12 | if (a < b) 13 | return a; 14 | else 15 | return b; 16 | } 17 | 18 | int main() 19 | { 20 | int x = 0, y = 0; 21 | 22 | cout << "Enter two integers: "; 23 | cin >> x >> y; 24 | cout << "The minimum is: " << Minimum(x, y) << endl; 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex8.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple user-defined type: struct 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | using std::string; 9 | 10 | struct Student 11 | { 12 | string name; 13 | float semesterGrades[5]; 14 | float gpa; 15 | }; 16 | 17 | int main() 18 | { 19 | Student s1; 20 | s1.name = "George Katz"; 21 | s1.semesterGrades[0] = 3.0; 22 | s1.semesterGrades[1] = 4.0; 23 | s1.gpa = 3.5; 24 | 25 | cout << s1.name << " has GPA: " << s1.gpa << endl; 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Chapter01/Chp1-Ex9.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple user-defined type: class (in simplist form) 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | using std::string; 9 | 10 | class Student 11 | { 12 | public: 13 | string name; 14 | float semesterGrades[5]; 15 | float gpa; 16 | }; 17 | 18 | int main() 19 | { 20 | Student s1; 21 | s1.name = "George Katz"; 22 | s1.semesterGrades[0] = 3.0; 23 | s1.semesterGrades[1] = 4.0; 24 | s1.gpa = 3.5; 25 | 26 | cout << s1.name << " has GPA: " << s1.gpa << endl; 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Chapter01/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full (and revised) program examples from Chapter 1. 2 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate simple I/O with iostreams 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | char name[20]; 11 | int age; 12 | cout << "Please enter a name and an age: "; 13 | cin >> name >> age; 14 | cout << "Hello " << name; 15 | cout << ". You are " << age << " years old." << endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex10.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple enum types 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | enum day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; 9 | 10 | enum workDay {Mon = 1, Tues, Wed, Thurs, Fri}; 11 | 12 | int main() 13 | { 14 | day birthday = Monday; 15 | workDay payday = Fri; 16 | 17 | cout << "Birthday is " << birthday << endl; 18 | cout << "Payday is " << payday << endl; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex11.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review namespaces (adding new and augmenting existing namespaces) 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | namespace DataTypes 9 | { 10 | int total; 11 | 12 | class LinkList 13 | { // full class definition ... 14 | }; 15 | 16 | class Stack 17 | { // full class definition ... 18 | }; 19 | }; 20 | 21 | namespace AbstractDataTypes 22 | { 23 | class Stack 24 | { // full class definition ... 25 | }; 26 | 27 | class Queue 28 | { // full class definition ... 29 | }; 30 | }; 31 | 32 | namespace AbstractDataTypes 33 | { 34 | int total; 35 | 36 | class Tree 37 | { // full class definition ... 38 | }; 39 | }; 40 | 41 | 42 | int main() 43 | { 44 | 45 | using namespace AbstractDataTypes; // activate namespace 46 | using DataTypes::LinkList; // activate only LinkList 47 | 48 | LinkList list1; // LinkList is found in DataTypes 49 | Stack stack1; // Stack is found in AbstractDataTypes 50 | 51 | total = 5; // from active AbstractDataTypes 52 | DataTypes::total = 85; // specify non-active member 53 | 54 | cout << "total " << total << "\n"; 55 | cout << "DataTypes::total " << DataTypes::total << endl; 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To illustrate basic iostream manipulators 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | char name[20]; 12 | float gpa; 13 | cout << "Please enter a name and a gpa: "; 14 | cin >> setw(20) >> name >> gpa; 15 | cout << "Hello " << name << flush; 16 | cout << ". GPA is: " << setprecision(3) << gpa << endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To review conditional statements 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int x; 11 | 12 | cout << "Enter an integer: "; 13 | cin >> x; 14 | 15 | if (x == 0) 16 | cout << "x is 0" << endl; 17 | else if (x < 0) 18 | cout << "x is negative" << endl; 19 | else 20 | { 21 | cout << "x is positive" << endl; 22 | cout << "and ten times x is: " << x*10 << endl; 23 | } 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To review simple looping with while and do-while 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int i = 0; 11 | 12 | while (i < 10) 13 | { 14 | cout << i << endl; 15 | i++; 16 | } 17 | 18 | i = 0; 19 | 20 | do 21 | { 22 | cout << i << endl; 23 | i++; 24 | } while (i < 10); 25 | 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple looping with for loops 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int i; 11 | 12 | for (i = 0; i < 10; i++) 13 | cout << i << endl; 14 | 15 | for (int j = 0; j < 10; j++) 16 | cout << j << endl; 17 | 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex6.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review nested for loops 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | for (int i = 0; i < 10; i++) 11 | { 12 | cout << i << endl; 13 | 14 | for (int j = 0; j < 10; j++) 15 | cout << j << endl; 16 | 17 | cout << "\n"; 18 | } 19 | 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review a simple function 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int minimum (int a, int b) 9 | { 10 | if (a < b) 11 | return a; 12 | else 13 | return b; 14 | } 15 | 16 | int main() 17 | { 18 | int x, y; 19 | 20 | cout << "Enter two integers: "; 21 | cin >> x >> y; 22 | cout << "The minimum is: " << minimum(x, y) << endl; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex8.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple user-defined type: struct 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | struct Student 10 | { 11 | char name[20]; 12 | float semesterGrades[5]; 13 | float gpa; 14 | }; 15 | 16 | int main() 17 | { 18 | Student s1; 19 | strcpy(s1.name, "George Katz"); 20 | s1.semesterGrades[0] = 3.0; 21 | s1.semesterGrades[1] = 4.0; 22 | s1.gpa = 3.5; 23 | 24 | cout << s1.name << " has GPA: " << s1.gpa << endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Chapter01/original/Chp1-Ex9.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple user-defined type: class (in simplist form) 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Student 10 | { 11 | public: 12 | char name[20]; 13 | float semesterGrades[5]; 14 | float gpa; 15 | }; 16 | 17 | int main() 18 | { 19 | Student s1; 20 | strcpy(s1.name, "George Katz"); 21 | s1.semesterGrades[0] = 3.0; 22 | s1.semesterGrades[1] = 4.0; 23 | s1.gpa = 3.5; 24 | 25 | cout << s1.name << " has GPA: " << s1.gpa << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Chapter01/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter02/Assessments/Chp2-Q2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Chp2, Question 2, a - d. Sample solution 3 | // Write a small C++ program to prompt a user to enter information regarding a Student, and print out the data. 4 | // a. Student information should minimally include first name, last name, gpa, and the current course in which 5 | // the Student is registered. This information may be stored in a simple class. You may utilize either char arrays 6 | // to represent the string fields since we have not yet covered pointers, or you may (preferably) utilize the string 7 | // type. Also, you may read in this information in the main function rather than creating a separate function to 8 | // read in the data (since the latter will require knowledge of pointers or references). Please do not use global 9 | // (i.e. extern variables). 10 | // b. Create a function to print out all the data for the Student. Remember to prototype this function. 11 | // Use a default value of 4.0 for gpa in the prototype of this function. Call this function two ways: once passing 12 | // in each argument explicitly, and once using the default gpa. 13 | // c. Now, overload the print function with one which either prints out selected data (i.e. last name and gpa) or 14 | // with a version of this function which takes a Student as an argument (but not a pointer or reference to a 15 | // Student – we’ll do that later). Remember to protype this function. 16 | // d. Use iostreams for I/O. 17 | 18 | #include 19 | #include 20 | 21 | using std::cout; // preferred to: using namespace std; 22 | using std::cin; 23 | using std::endl; 24 | using std::string; 25 | 26 | class Student 27 | { 28 | public: 29 | string firstName; 30 | string lastName; 31 | float gpa; 32 | string course; 33 | }; 34 | 35 | void Print(string, string, string, float = 4.0); 36 | void Print(string, float); 37 | void Print(Student); 38 | 39 | int main() 40 | { 41 | Student s1; 42 | 43 | cout << "Please enter : "; 44 | cin >> s1.firstName >> s1.lastName; 45 | cout << "Please enter " << s1.firstName << " " << s1.lastName; 46 | cout << "'s and : "; 47 | cin >> s1.gpa >> s1.course; 48 | 49 | Print(s1.firstName, s1.lastName, s1.course, s1.gpa); 50 | Print(s1.firstName, s1.lastName, s1.course); // use default gpa 51 | Print(s1.lastName, s1.gpa); // use overloaded fn. 52 | 53 | return 0; 54 | } 55 | 56 | void Print(string fn, string ln, string course, float gpa) 57 | { 58 | cout << fn << " " << ln << " is taking " << course; 59 | cout << " and has a gpa of " << std::setprecision(3) << gpa << endl; 60 | } 61 | 62 | void Print(string ln, float gpa) 63 | { 64 | cout << ln << " has gpa of " << std::setprecision(3) << gpa << endl; 65 | } 66 | 67 | void Print(Student s) 68 | { 69 | cout << s.firstName << " " << s.lastName << " is taking " << s.course; 70 | cout << " and has a gpa of " << std::setprecision(3) << s.gpa << endl; 71 | } 72 | 73 | -------------------------------------------------------------------------------- /Chapter02/Assessments/ReadMeChp2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter02/Assessments/ReadMeChp2.pdf -------------------------------------------------------------------------------- /Chapter02/Chp2-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrate use of const qualified variables 3 | 4 | #include 5 | #include 6 | #include // don't worry, the cstring illustrates an eductional point, demonstrating how a const can be 7 | // used to size an array. It could be an array of any type, but the char [] allows us to 8 | // illustrate two uses of const qualification. Don't worry, we'll generally use std::string. 9 | 10 | using std::cout; // preferred to: using namespace std; 11 | using std::cin; 12 | using std::endl; 13 | using std::setw; 14 | 15 | const int MAX = 50; // simple const variable declaration and initialization 16 | 17 | constexpr int LARGEST = 50; // simple constexpr variable declaration and initialization 18 | 19 | constexpr int Minimum(int a, int b) // function's return value is a constexpr 20 | { 21 | return (a < b) ? a : b; 22 | } 23 | 24 | int main() 25 | { 26 | int x = 0, y = 0; 27 | constexpr int a = 10, b = 15; // note: const applies to both a and b; note: variables not being used in 28 | // same sense as a #define, so not capitalized here out of convention 29 | cout << "Enter two values: "; 30 | cin >> x >> y; 31 | const int min = Minimum(x, y); // const variable initialized with a function's return value 32 | cout << "Minimum is: " << min << endl; 33 | 34 | constexpr int smallest = Minimum(a, b); // constexpr variable initialized with return value of constexpr fn 35 | cout << "Smallest of " << a << " " << b << " is: " << smallest << endl; 36 | 37 | char bigName[MAX] = {""}; // const variable used to size an array 38 | char largeName[LARGEST] = {""}; // constexpr used to size an array 39 | cout << "Enter two names: "; 40 | cin >> setw(MAX) >> bigName >> setw(LARGEST) >> largeName; 41 | const int namelen = strlen(bigName); // a const can be initialized with a calculated value 42 | cout << "Length of name 1: " << namelen << endl; 43 | cout << "Length of name 2: " << strlen(largeName) << endl; 44 | 45 | return 0; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Chapter02/Chp2-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Demonstrate simple function prototyping 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | [[nodiscard]] int Minimum(int, int); // function prototype. Note optional use of 'nodiscard' 10 | 11 | 12 | int main() 13 | { 14 | int x = 5, y = 89; 15 | cout << Minimum(x, y) << endl; // function call with actual parameters 16 | // Minimum(x, y); // function call that ignores return value will issue a warning 17 | 18 | return 0; 19 | } 20 | 21 | [[nodiscard]] int Minimum(int a, int b) // function definition with formal parameters 22 | { 23 | if (a < b) 24 | return a; 25 | else 26 | return b; 27 | } 28 | -------------------------------------------------------------------------------- /Chapter02/Chp2-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrate optional names for arguments in function prototype 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | [[nodiscard]] int Minimum(int arg1, int arg2); // function prototype with optional argument names 10 | 11 | 12 | int main() 13 | { 14 | int x = 5; 15 | int y = 89; 16 | cout << Minimum(x, y) << endl; // function call with actual parameters 17 | 18 | return 0; 19 | } 20 | 21 | [[nodiscard]] int Minimum(int a, int b) // function definition with formal parameters 22 | { 23 | if (a < b) 24 | return a; 25 | else 26 | return b; 27 | } 28 | -------------------------------------------------------------------------------- /Chapter02/Chp2-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrate default value usage in a function prototype 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | [[nodiscard]] int Minimum(int arg1, int arg2 = 100000); // function prototype 10 | // with one default value 11 | 12 | int main() 13 | { 14 | int x = 5; 15 | int y = 89; 16 | cout << Minimum(x) << endl; // function call with only one argument 17 | // (i.e. uses default value) 18 | cout << Minimum(x, y) << endl; // no default values used 19 | 20 | return 0; 21 | } 22 | 23 | [[nodiscard]] int Minimum(int a, int b) // function definition with formal parameters 24 | { 25 | if (a < b) 26 | return a; 27 | else 28 | return b; 29 | } 30 | -------------------------------------------------------------------------------- /Chapter02/Chp2-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrate prototyping in different scopes with different default values 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | [[nodiscard]] int Minimum(int, int); // standard function prototype 10 | 11 | void Function1(int x) 12 | { 13 | [[nodiscard]] int Minimum(int arg1, int arg2 = 500); // local prototype with default value 14 | 15 | cout << Minimum(x) << endl; 16 | } 17 | 18 | void Function2(int x) 19 | { 20 | [[nodiscard]] int Minimum(int arg1, int arg2 = 90); // local prototype with default value 21 | 22 | cout << Minimum(x) << endl; 23 | } 24 | 25 | [[nodiscard]] int Minimum(int a, int b) // function definition with formal parameters 26 | { 27 | if (a < b) 28 | return a; 29 | else 30 | return b; 31 | } 32 | 33 | int main() 34 | { 35 | Function1(30); 36 | Function2(450); 37 | 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Chapter02/Chp2-Ex6.cpp: -------------------------------------------------------------------------------- 1 | // (c) 1994 - 2020 Dorothy R. Kirk 2 | // Purpose: To illustrate function overloading 3 | 4 | #include 5 | #include 6 | 7 | using std::cout; // preferred to: using namespace std; 8 | using std::endl; 9 | 10 | constexpr float PI = 3.14159; 11 | 12 | class Circle // user defined type declarations 13 | { 14 | public: 15 | float radius; 16 | float area; 17 | }; 18 | 19 | class Rectangle 20 | { 21 | public: 22 | float length; 23 | float width; 24 | float area; 25 | }; 26 | 27 | void Display(Circle); // function prototypes 28 | void Display(Rectangle); // These functions are overloaded 29 | // since they differ in signature 30 | 31 | int main() 32 | { 33 | Circle myCircle; 34 | Rectangle myRect; 35 | Rectangle mySquare; 36 | 37 | myCircle.radius = 5.0; 38 | myCircle.area = PI * pow(myCircle.radius, 2.0); 39 | 40 | myRect.length = 2.0; 41 | myRect.width = 4.0; 42 | myRect.area = myRect.length * myRect.width; 43 | 44 | mySquare.length = 4.0; 45 | mySquare.width = 4.0; 46 | mySquare.area = mySquare.length * mySquare.width; 47 | 48 | Display(myCircle); 49 | Display(myRect); 50 | Display(mySquare); 51 | 52 | return 0; 53 | } 54 | 55 | void Display (Circle c) 56 | { 57 | cout << "Circle with radius " << c.radius << " has an area of "; 58 | cout << c.area << endl; 59 | } 60 | 61 | void Display (Rectangle r) 62 | { 63 | cout << "Rectangle with length " << r.length << " and width "; 64 | cout << r.width << " has an area of " << r.area << endl; 65 | } 66 | 67 | -------------------------------------------------------------------------------- /Chapter02/Chp2-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple type conversion 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | [[nodiscard]] int Maximum (double, double); 10 | 11 | int main() 12 | { 13 | int result = 0; 14 | int m = 6, n = 10; 15 | float x = 5.7, y = 9.89; 16 | 17 | result = Maximum(x, y); 18 | cout << "Result is: " << result << endl; 19 | cout << "The maximum is: " << Maximum(m, n) << endl; 20 | 21 | return 0; 22 | } 23 | 24 | [[nodiscard]] int Maximum (double a, double b) 25 | { 26 | return (a > b) ? a : b; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Chapter02/Chp2-Ex8.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple type conversion 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | [[nodiscard]] int Maximum (int, int); // overloaded fn prototypes. 10 | [[nodiscard]] float Maximum (float, float); // Return type is not part of the signature 11 | 12 | int main() 13 | { 14 | char a = 'A', b = 'B'; 15 | float x = 5.7, y = 9.89; 16 | int m = 6, n = 10; 17 | 18 | cout << "The maximum is: " << Maximum(a, b) << endl; 19 | cout << "The maximum is: " << Maximum(x, y) << endl; 20 | cout << "The maximum is: " << Maximum(m, n) << endl; 21 | // Note: the following line would generate a compiler error since 22 | // there are two equally good candidates -- hence "ambiguous" 23 | // cout << "The maximum is: " << Maximum(a, y) << endl; 24 | // We can force a choice through using an explicit typecast 25 | cout << "The maximum is: " << Maximum(static_cast(a), y) << endl; 26 | 27 | return 0; 28 | } 29 | 30 | [[nodiscard]] int Maximum (int arg1, int arg2) 31 | { 32 | if (arg1 > arg2) 33 | return arg1; 34 | else 35 | return arg2; 36 | } 37 | 38 | [[nodiscard]] float Maximum (float arg1, float arg2) 39 | { 40 | if (arg1 > arg2) 41 | return arg1; 42 | else 43 | return arg2; 44 | } 45 | -------------------------------------------------------------------------------- /Chapter02/ReadMe: -------------------------------------------------------------------------------- 1 | This directory contains the full program examples which accompany Chapter 2. 2 | -------------------------------------------------------------------------------- /Chapter02/original/Chp2-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrate use of const qualified variables 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | // simple const variable declaration and initialization 11 | const int MAX = 50; 12 | 13 | int minimum(int a, int b) 14 | { 15 | if (a < b) 16 | return a; 17 | else 18 | return b; 19 | } 20 | 21 | int main() 22 | { 23 | int x, y; 24 | cout << "Enter two values: "; 25 | cin >> x >> y; 26 | const int MIN = minimum(x, y); // const variable initialized 27 | // with a function's return value 28 | cout << "Minimum is: " << MIN << endl; 29 | 30 | char bigName[MAX]; // const variable used to size an array 31 | cout << "Enter a name: "; 32 | cin >> setw(MAX) >> bigName; 33 | const int NAMELEN = strlen(bigName); 34 | cout << "Length of name: " << NAMELEN << endl; 35 | 36 | return 0; 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Chapter02/original/Chp2-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Demonstrate simple function prototyping 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int minimum(int, int); // function prototype 9 | 10 | 11 | int main() 12 | { 13 | int x = 5; 14 | int y = 89; 15 | cout << minimum(x, y) << endl; // function call with actual parameters 16 | 17 | return 0; 18 | } 19 | 20 | int minimum(int a, int b) // function definition with formal parameters 21 | { 22 | if (a < b) 23 | return a; 24 | else 25 | return b; 26 | } 27 | -------------------------------------------------------------------------------- /Chapter02/original/Chp2-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrate optional names for arguments in function prototype 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int minimum(int arg1, int arg2); // function prototype with optional argument names 9 | 10 | 11 | int main() 12 | { 13 | int x = 5; 14 | int y = 89; 15 | cout << minimum(x, y) << endl; // function call with actual parameters 16 | 17 | return 0; 18 | } 19 | 20 | int minimum(int a, int b) // function definition with formal parameters 21 | { 22 | if (a < b) 23 | return a; 24 | else 25 | return b; 26 | } 27 | -------------------------------------------------------------------------------- /Chapter02/original/Chp2-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (c) 2020 Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrate default value usage in a function prototype 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int minimum(int arg1, int arg2 = 100000); // function prototype 9 | // with one default value 10 | 11 | 12 | int main() 13 | { 14 | int x = 5; 15 | int y = 89; 16 | cout << minimum(x) << endl; // function call with only one argument 17 | // (i.e. uses default value) 18 | cout << minimum(x, y) << endl; // no default values used 19 | 20 | return 0; 21 | } 22 | 23 | int minimum(int a, int b) // function definition with formal parameters 24 | { 25 | if (a < b) 26 | return a; 27 | else 28 | return b; 29 | } 30 | -------------------------------------------------------------------------------- /Chapter02/original/Chp2-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrate prototyping in different scopes 3 | // with different default values 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int minimum(int, int); // standard function prototype 10 | 11 | void function1(int x) 12 | { 13 | int minimum(int arg1, int arg2 = 500); // local prototype with default value 14 | 15 | cout << minimum(x) << endl; 16 | } 17 | 18 | void function2(int x) 19 | { 20 | int minimum(int arg1, int arg2 = 90); // local prototype with default value 21 | 22 | cout << minimum(x) << endl; 23 | } 24 | 25 | int minimum(int a, int b) // function definition with formal parameters 26 | { 27 | if (a < b) 28 | return a; 29 | else 30 | return b; 31 | } 32 | 33 | int main() 34 | { 35 | function1(30); 36 | function2(450); 37 | 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Chapter02/original/Chp2-Ex6.cpp: -------------------------------------------------------------------------------- 1 | // (c) 1994 - 2020 Dorothy R. Kirk 2 | // Purpose: To illustrate function overloading 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | const float PI = 3.14159; 10 | 11 | class Circle // user defined type declarations 12 | { 13 | public: 14 | float radius; 15 | float area; 16 | }; 17 | 18 | class Rectangle 19 | { 20 | public: 21 | float length; 22 | float width; 23 | float area; 24 | }; 25 | 26 | void display(Circle); // function prototypes 27 | void display(Rectangle); // These functions are overloaded 28 | // since they differ in signature 29 | 30 | int main() 31 | { 32 | Circle myCircle; 33 | Rectangle myRect; 34 | Rectangle mySquare; 35 | 36 | myCircle.radius = 5.0; 37 | myCircle.area = PI * pow(myCircle.radius, 2.0); 38 | 39 | myRect.length = 2.0; 40 | myRect.width = 4.0; 41 | myRect.area = myRect.length * myRect.width; 42 | 43 | mySquare.length = 4.0; 44 | mySquare.width = 4.0; 45 | mySquare.area = mySquare.length * mySquare.width; 46 | 47 | display(myCircle); 48 | display(myRect); 49 | display(mySquare); 50 | 51 | return 0; 52 | } 53 | 54 | void display (Circle c) 55 | { 56 | cout << "Circle with radius " << c.radius << " has an area of "; 57 | cout << c.area << endl; 58 | } 59 | 60 | void display (Rectangle r) 61 | { 62 | cout << "Rectangle with length " << r.length << " and width "; 63 | cout << r.width << " has an area of " << r.area << endl; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /Chapter02/original/Chp2-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple type conversion 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int maximum (double, double); 9 | 10 | int main() 11 | { 12 | int result; 13 | int m = 6, n = 10; 14 | float x = 5.7, y = 9.89; 15 | 16 | result = maximum(x, y); 17 | cout << "Result is: " << result << endl; 18 | cout << "The maximum is: " << maximum(m, n) << endl; 19 | 20 | return 0; 21 | } 22 | 23 | int maximum (double a, double b) 24 | { 25 | if (a > b) 26 | return a; 27 | else 28 | return b; 29 | } 30 | -------------------------------------------------------------------------------- /Chapter02/original/Chp2-Ex8.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Review simple type conversion 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int maximum (int, int); // overloaded fn prototypes. 9 | float maximum (float, float); // Return type is not part of the signature 10 | 11 | int main() 12 | { 13 | char a = 'A', b = 'B'; 14 | float x = 5.7, y = 9.89; 15 | int m = 6, n = 10; 16 | 17 | cout << "The maximum is: " << maximum(a, b) << endl; 18 | cout << "The maximum is: " << maximum(x, y) << endl; 19 | cout << "The maximum is: " << maximum(m, n) << endl; 20 | // Note: the following line would generate a compiler error since 21 | // there are two equally good candidates -- hence "ambiguous" 22 | // cout << "The maximum is: " << maximum(a, y) << endl; 23 | // We can force a choice through using an explicit typecast 24 | cout << "The maximum is: " << maximum((float)a, y) << endl; 25 | 26 | return 0; 27 | } 28 | 29 | int maximum (int arg1, int arg2) 30 | { 31 | if (arg1 > arg2) 32 | return arg1; 33 | else 34 | return arg2; 35 | } 36 | 37 | float maximum (float arg1, float arg2) 38 | { 39 | if (arg1 > arg2) 40 | return arg1; 41 | else 42 | return arg2; 43 | } 44 | -------------------------------------------------------------------------------- /Chapter02/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter03/Assessments/Chp3-Q2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Chapter 3, Question 2 - sample solution 3 | 4 | // Write the following pointer declarations which include a const qualification: 5 | // a. Write a declaration for a pointer to a constant object. Assume the object is of type Student. 6 | // Hint: read your declaration from right to left to verify correctness. 7 | // b. Write a declaration for a constant pointer to a non-constant object. Again, assume the object is of type Student. 8 | // c. Write a declaration for a constant pointer to a constant object. The object will again be of type Student. 9 | 10 | #include 11 | 12 | using std::string; 13 | 14 | class Student 15 | { 16 | public: 17 | string name; 18 | }; 19 | 20 | int main() 21 | { 22 | Student *s0 = new Student; 23 | const Student *s1; 24 | Student *const s2 = s0; 25 | const Student *const s3 = s0; 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Chapter03/Assessments/ReadMeChp3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter03/Assessments/ReadMeChp3.pdf -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Simple pointer to user-defined type example 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | struct collection 10 | { 11 | int x; 12 | float y; 13 | }; 14 | 15 | 16 | int main() 17 | { 18 | collection *item = nullptr; // pointer declaration and initialization 19 | 20 | item = new collection; // memory allocation 21 | item->x = 9; // use -> to access data member x 22 | (*item).y = 120.77; // alternative notation to access member y 23 | cout << (*item).x << " " << item->y << endl; 24 | 25 | delete item; 26 | 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Dynamically allocating single dimension array 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::cin; 8 | using std::endl; 9 | using std::flush; 10 | 11 | struct collection 12 | { 13 | int x; 14 | float y; 15 | }; 16 | 17 | 18 | int main() 19 | { 20 | int numElements = 0, *intArray = nullptr; // int and pointer declaration with initializations 21 | collection *collectionArray = nullptr; // pointer declaration and initialization 22 | 23 | cout << "How many elements would you like? " << flush; 24 | cin >> numElements; 25 | 26 | intArray = new int[numElements]; 27 | collectionArray = new collection[numElements]; 28 | 29 | for (int i = 0; i < numElements; i++) 30 | { 31 | intArray[i] = i; // load each array with values 32 | collectionArray[i].x = i; // using arrray notation [] 33 | collectionArray[i].y = i + .5; 34 | 35 | // alternatively use pointer notation to print values 36 | cout << *(intArray + i) << " "; 37 | cout << (*(collectionArray + i)).y << endl; 38 | } 39 | 40 | // mark memory for deletion 41 | delete [] intArray; // for an array of primitive types, delete intArray; is also ok 42 | delete [] collectionArray; // the []'s on delete first call a 'cleanup' function on each element before reclaiming 43 | // the heap memory (useful for user defined types)-- more on that with Chapter 5 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Dynamically allocated 2-D array - using an array of pointers 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::cin; 8 | using std::endl; 9 | using std::flush; 10 | 11 | constexpr int NUMROWS = 5; 12 | 13 | int main() 14 | { 15 | // float *TwoDimArray[NUMROWS]; // caution - this array is uninitialized, so the following declaration is preferrred 16 | float *TwoDimArray[NUMROWS] = {nullptr, nullptr, nullptr, nullptr, nullptr}; // alternatively, initialize each element to nullptr 17 | int numColumns = 0; 18 | 19 | cout << "Enter number of columns: " << flush; 20 | cin >> numColumns; 21 | 22 | for (int i = 0; i < NUMROWS; i++) 23 | { 24 | // allocate column quantity for each row 25 | TwoDimArray[i] = new float[numColumns]; 26 | 27 | // load each column entry with dta 28 | for (int j = 0; j < numColumns; j++) 29 | { 30 | TwoDimArray[i][j] = i + j + .05; 31 | cout << TwoDimArray[i][j] << " "; 32 | 33 | } 34 | cout << endl; 35 | } 36 | 37 | for (int i = 0; i < NUMROWS; i++) 38 | delete [] TwoDimArray[i]; // delete column quantities for each row 39 | // note: delete TwoDimArray[i]; would also work since this is of a standard type 40 | // (the []'s ensure a clean up fn is called on each element -- useful for user defined types) 41 | // more on that when we talk about classes in detail in Chapter 5 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Dynamically allocated 2-D array - using a pointer to a pointer 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::cin; 8 | using std::endl; 9 | using std::flush; 10 | 11 | int main() 12 | { 13 | int numRows = 0, numColumns = 0; 14 | float **TwoDimArray = nullptr; 15 | 16 | cout << "Enter number of rows: " << flush; 17 | cin >> numRows; 18 | TwoDimArray = new float * [numRows]; // allocate row pointers 19 | 20 | cout << "Enter number of columns: " << flush; 21 | cin >> numColumns; 22 | 23 | for (int i = 0; i < numRows; i++) 24 | { 25 | // allocate column quantity for each row 26 | TwoDimArray[i] = new float[numColumns]; 27 | 28 | // load each column entry with dta 29 | for (int j = 0; j < numColumns; j++) 30 | { 31 | TwoDimArray[i][j] = i + j + .05; 32 | cout << TwoDimArray[i][j] << " "; 33 | 34 | } 35 | cout << endl; 36 | } 37 | 38 | for (int i = 0; i < numRows; i++) 39 | delete [] TwoDimArray[i]; // delete columns for each row -- note: delete TwoDimArray[i]; is also ok since primitive type 40 | delete [] TwoDimArray; // delete allocated rows -- note: delete TwoDimAray; also ok since primitive type 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Dynamically allocated 3-D array - using a pointer to a pointer 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::cin; 8 | using std::endl; 9 | using std::flush; 10 | 11 | int main() 12 | { 13 | int dim1 = 0, dim2 = 0, dim3 = 0; 14 | int ***ThreeDimArray = nullptr; 15 | 16 | cout << "Enter dim 1, dim 2, dim 3: " << flush; 17 | cin >> dim1 >> dim2 >> dim3; 18 | ThreeDimArray = new int ** [dim1]; // allocate dim 1 19 | 20 | for (int i = 0; i < dim1; i++) 21 | { 22 | ThreeDimArray[i] = new int * [dim2]; // allocate dim 2 23 | 24 | for (int j = 0; j < dim2; j++) 25 | { 26 | ThreeDimArray[i][j] = new int [dim3]; // allocate dim 3 27 | for (int k = 0; k < dim3; k++) 28 | { 29 | ThreeDimArray[i][j][k] = i + j + k; 30 | cout << ThreeDimArray[i][j][k] << " "; 31 | } 32 | cout << endl; 33 | 34 | } 35 | cout << endl; 36 | } 37 | 38 | for (int i = 0; i < dim1; i++) 39 | { 40 | for (int j = 0; j < dim2; j++) 41 | delete [] ThreeDimArray[i][j]; // release dim 3 42 | delete [] ThreeDimArray[i]; // release dim 2 43 | } 44 | delete [] ThreeDimArray; // release dim 1 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex6.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates pointers are arguments to functions 3 | 4 | #include 5 | using std::cout; // preferred to: using namespace std; 6 | using std::endl; 7 | 8 | 9 | void TryToAddOne(int); 10 | void AddOne(int *); 11 | 12 | int main() 13 | { 14 | int x = 10; 15 | int *y = nullptr; 16 | 17 | y = new int; 18 | *y = 15; 19 | 20 | cout << "x: " << x << " and *y: " << *y << endl; 21 | 22 | TryToAddOne(x); // unsuccessful, call by value 23 | TryToAddOne(*y); 24 | cout << "x: " << x << " and *y: " << *y << endl; 25 | 26 | AddOne(&x); // successful, passing a pointer 27 | AddOne(y); 28 | cout << "x: " << x << " and *y: " << *y << endl; 29 | 30 | delete y; // relinquish the heap memory 31 | 32 | return 0; 33 | } 34 | 35 | void TryToAddOne(int arg) 36 | { 37 | arg++; 38 | } 39 | 40 | void AddOne(int *arg) 41 | { 42 | (*arg)++; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates a pointer as a return type from a function 3 | // Let's try not to get worked up that a char * is demonstrated. This is a chapter about pointers! 4 | // You'll need to have some facility using a char * on occasion, even if we prefer a string most elsewhere. 5 | 6 | #include 7 | #include 8 | 9 | using std::cin; // preferred to: using namespace std; 10 | using std::cout; 11 | using std::endl; 12 | using std::flush; 13 | using std::setw; 14 | 15 | constexpr int MAX = 20; 16 | 17 | [[nodiscard]] char *createName(); // function prototype 18 | 19 | int main() 20 | { 21 | char *name = nullptr; 22 | name = createName(); 23 | cout << "Name: " << name << endl; 24 | delete [] name; // notice that we delete in a different scope than that which we allocated. 25 | // this is a motivation for us later choosing a smart pointer (to alleviate unintentional errors) 26 | return 0; // Also note that delete name; would have been ok (primitive type) 27 | } 28 | 29 | [[nodiscard]] char *createName() 30 | { 31 | char *temp = new char[MAX]; 32 | cout << "Enter name: " << flush; 33 | cin >> setw(MAX) >> temp; // setw ensures we don't overflow the input buffer 34 | return temp; 35 | } 36 | -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex8.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates a pointer to const qualifed data as a function argument 3 | // and as a return type from a function 4 | // Note: A const char * is used here for educational purposes (this is a chapter featuring pointers). 5 | // Not to worry, we'll use a string whenever possible, but we're trying to illustrate a pointer concept right now. 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | using std::cout; // preferred to: using namespace std; 12 | using std::endl; 13 | 14 | char suffix = 'A'; 15 | 16 | const char *GenId(const char *); // function prototype 17 | 18 | int main() 19 | { 20 | const char *newId1 = nullptr, *newId2 = nullptr; 21 | newId1 = GenId("Group"); // fn call will allocate memory 22 | newId2 = GenId("Group"); // fn call will allocate memory 23 | cout << "New ids: " << newId1 << " " << newId2 << endl; 24 | delete [] newId1; // notice that we are deallocating in a different scope than we allocated. 25 | delete [] newId2; // this will give us motivation later to use a smart pointer for safety. 26 | // note: delete newId1; or delete newId2; would also be ok (primitive type) 27 | 28 | return 0; 29 | } 30 | 31 | const char *GenId(const char *base) 32 | { 33 | char *temp = new char[strlen(base) + 2]; // One extra space for suffix plus null 34 | strcpy(temp, base); 35 | temp[strlen(base)] = suffix++; // append suffix to base 36 | temp[strlen(base) + 1] = '\0'; // add null character 37 | return temp; // temp will be up-cast to a const char * to be treated more 38 | // restrictively than it was defined 39 | } 40 | -------------------------------------------------------------------------------- /Chapter03/Chp3-Ex9.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To illustrate void pointers 3 | // Note: void *'s must be used with extreme caution. 4 | // They are illustrated because you may see them in existing code. You may prefer to use a template to genericize a type 5 | // (we'll later see that a template will expand for each actual type, whereas a void * does not) 6 | 7 | #include 8 | 9 | using std::cout; // preferred to: using namespace std; 10 | using std::endl; 11 | 12 | int main() 13 | { 14 | void *unspecified = nullptr; // the void * may point to any data type 15 | int *x = nullptr; 16 | 17 | unspecified = new int; // the void * now points to an int 18 | 19 | // the void * must be vase to an int * before it is dereferenced 20 | *(static_cast(unspecified)) = 89; 21 | 22 | // let x point to the memory which unspecified points to 23 | x = static_cast (unspecified); 24 | 25 | cout << *x << " " << *(static_cast(unspecified)) << endl; 26 | 27 | delete static_cast(unspecified); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Chapter03/ReadMe: -------------------------------------------------------------------------------- 1 | This directory contains the full program examples which accompany Chapter 3. 2 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Simple pointer to user-defined type example 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct collection 9 | { 10 | int x; 11 | float y; 12 | }; 13 | 14 | 15 | int main() 16 | { 17 | collection *item; // pointer declaration 18 | 19 | item = new collection; // memory allocation 20 | item->x = 9; // use -> to access data member x 21 | (*item).y = 120.77; // alternative notation to access member y 22 | cout << (*item).x << " " << item->y << endl; 23 | 24 | delete item; 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Dynamically allocating single dimension array 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct collection 9 | { 10 | int x; 11 | float y; 12 | }; 13 | 14 | 15 | int main() 16 | { 17 | int numElements, *intArray; // int and pointer declaration 18 | collection *collectionArray; // pointer declaration 19 | 20 | cout << "How many elements would you like? " << flush; 21 | cin >> numElements; 22 | 23 | intArray = new int[numElements]; 24 | collectionArray = new collection[numElements]; 25 | 26 | for (int i = 0; i < numElements; i++) 27 | { 28 | intArray[i] = i; // load each array with values 29 | collectionArray[i].x = i; // using arrray notation [] 30 | collectionArray[i].y = i + .5; 31 | 32 | // alternatively use pointer notation to print values 33 | cout << *(intArray + i) << " "; 34 | cout << (*(collectionArray + i)).y << endl; 35 | } 36 | delete intArray; // mark memory for deletion 37 | delete [] collectionArray; 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Dynamically allocated 2-D array - using an array of pointers 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | const int NUMROWS = 5; 9 | 10 | int main() 11 | { 12 | float *TwoDimArray[NUMROWS]; 13 | int numColumns; 14 | 15 | cout << "Enter number of columns: " << flush; 16 | cin >> numColumns; 17 | 18 | for (int i = 0; i < NUMROWS; i++) 19 | { 20 | // allocate column quantity for each row 21 | TwoDimArray[i] = new float[numColumns]; 22 | 23 | // load each column entry with dta 24 | for (int j = 0; j < numColumns; j++) 25 | { 26 | TwoDimArray[i][j] = i + j + .05; 27 | cout << TwoDimArray[i][j] << " "; 28 | 29 | } 30 | cout << endl; 31 | } 32 | 33 | for (int i = 0; i < NUMROWS; i++) 34 | delete TwoDimArray[i]; // delete column for each row 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Dynamically allocated 2-D array - using a pointer to a pointer 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | int main() 10 | { 11 | int numRows, numColumns; 12 | float **TwoDimArray; 13 | 14 | cout << "Enter number of rows: " << flush; 15 | cin >> numRows; 16 | TwoDimArray = new float * [numRows]; // allocate row pointers 17 | 18 | cout << "Enter number of columns: " << flush; 19 | cin >> numColumns; 20 | 21 | for (int i = 0; i < numRows; i++) 22 | { 23 | // allocate column quantity for each row 24 | TwoDimArray[i] = new float[numColumns]; 25 | 26 | // load each column entry with dta 27 | for (int j = 0; j < numColumns; j++) 28 | { 29 | TwoDimArray[i][j] = i + j + .05; 30 | cout << TwoDimArray[i][j] << " "; 31 | 32 | } 33 | cout << endl; 34 | } 35 | 36 | for (int i = 0; i < numRows; i++) 37 | delete TwoDimArray[i]; // delete column for each row 38 | delete TwoDimArray; // delete allocated rows 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Dynamically allocated 3-D array - using a pointer to a pointer 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | int main() 10 | { 11 | int dim1, dim2, dim3; 12 | int ***ThreeDimArray; 13 | 14 | cout << "Enter dim 1, dim 2, dim 3: " << flush; 15 | cin >> dim1 >> dim2 >> dim3; 16 | ThreeDimArray = new int ** [dim1]; // allocate dim 1 17 | 18 | for (int i = 0; i < dim1; i++) 19 | { 20 | ThreeDimArray[i] = new int * [dim2]; // allocate dim 2 21 | 22 | for (int j = 0; j < dim2; j++) 23 | { 24 | ThreeDimArray[i][j] = new int [dim3]; // allocate dim 3 25 | for (int k = 0; k < dim3; k++) 26 | { 27 | ThreeDimArray[i][j][k] = i + j + k; 28 | cout << ThreeDimArray[i][j][k] << " "; 29 | } 30 | cout << endl; 31 | 32 | } 33 | cout << endl; 34 | } 35 | 36 | for (int i = 0; i < dim1; i++) 37 | { 38 | for (int j = 0; j < dim2; j++) 39 | delete ThreeDimArray[i][j]; // release dim 3 40 | delete ThreeDimArray[i]; // release dim 2 41 | } 42 | delete ThreeDimArray; // release dim 1 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex6.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates pointers are arguments to functions 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | void TryToAddOne(int); 9 | void AddOne(int *); 10 | 11 | int main() 12 | { 13 | int x = 10; 14 | int *y; 15 | 16 | y = new int; 17 | *y = 15; 18 | 19 | cout << "x: " << x << " and *y: " << *y << endl; 20 | 21 | TryToAddOne(x); // unsuccessful, call by value 22 | TryToAddOne(*y); 23 | cout << "x: " << x << " and *y: " << *y << endl; 24 | 25 | AddOne(&x); // successful, passing a pointer 26 | AddOne(y); 27 | cout << "x: " << x << " and *y: " << *y << endl; 28 | 29 | return 0; 30 | } 31 | 32 | void TryToAddOne(int arg) 33 | { 34 | arg++; 35 | } 36 | 37 | void AddOne(int *arg) 38 | { 39 | (*arg)++; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates a pointer as a return type from a function 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | const int MAX = 20; 9 | 10 | char *createName(); // function prototype 11 | 12 | int main() 13 | { 14 | char *name; 15 | name = createName(); 16 | cout << "Name: " << name << endl; 17 | delete name; 18 | 19 | return 0; 20 | } 21 | 22 | char *createName() 23 | { 24 | char *temp = new char[MAX]; 25 | cout << "Enter name: " << flush; 26 | cin >> setw(MAX) >> temp; 27 | return temp; 28 | } 29 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex8.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates a pointer to const qualifed data as a function argument 3 | // and as a return type from a function 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | char suffix = 'A'; 12 | 13 | const char *genId(const char *); // function prototype 14 | 15 | int main() 16 | { 17 | const char *newId1, *newId2; 18 | newId1 = genId("Group"); // fn call will allocate memory 19 | newId2 = genId("Group"); // fn call will allocate memory 20 | cout << "New ids: " << newId1 << " " << newId2 << endl; 21 | delete newId1; 22 | delete newId2; 23 | 24 | return 0; 25 | } 26 | 27 | const char *genId(const char *base) 28 | { 29 | char *temp = new char[strlen(base) + 2]; // One extra space for suffix plus null 30 | strcpy(temp, base); 31 | temp[strlen(base)] = suffix++; // append suffix to base 32 | temp[strlen(base) + 1] = '\0'; // add null character 33 | return temp; // temp will be up-cast to a const char * to be treated more 34 | // restrictively than it was defined 35 | } 36 | -------------------------------------------------------------------------------- /Chapter03/original/Chp3-Ex9.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To illustrate void pointers 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | void *unspecified; // the void * may point to any data type 11 | int *x; 12 | 13 | unspecified = new int; // the void * now points to an int 14 | 15 | // the void * must be vase to an int * before it is dereferenced 16 | *((int *) unspecified) = 89; 17 | 18 | // let x point to the memory which unspecified points to 19 | x = (int *) unspecified; 20 | 21 | cout << *x << " " << *((int *) unspecified) << endl; 22 | 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Chapter03/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter04/Assessments/Chp4-Q1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Chapter 4, Question 1, a - c, Sample Solution 3 | 4 | // Modify and augment your C++ program from Chapter 3, Indirect Addressing – Pointers, Exercise 1 as follows: 5 | // a. Overload your ReadData() function, with a version that accepts a Student & parameter to allow firstName, 6 | // lastName, currentCourseEnrolled, and gpa to be entered from the keyboard within the function. 7 | // b. Replace the Print() function which takes a Student from your previous solution to instead take a const 8 | // Student & as a parameter for Print(). 9 | // c. Create variables of type Student and of type Student * in main(). Now, call the various versions of 10 | // ReadData(), and Print(). 11 | 12 | #include 13 | #include 14 | 15 | using std::cout; // preferred to: using namespace std; 16 | using std::cin; 17 | using std::endl; 18 | using std::string; 19 | 20 | constexpr int MAX = 5; 21 | 22 | class Student 23 | { 24 | public: 25 | string firstName; 26 | string lastName; 27 | float gpa; 28 | string course; 29 | }; 30 | 31 | // function prototypes 32 | void Print(const Student *); 33 | void Print(const Student &); // note: this version is instead of void Print(Student); Having both creates ambiguity 34 | void ReadData(Student *); 35 | void ReadData(Student &); 36 | 37 | int main() 38 | { 39 | Student s1, s2; 40 | Student *s3 = new Student; 41 | Student *s4 = new Student; 42 | ReadData(s1); // reference version 43 | ReadData(&s2); // pointer version 44 | ReadData(s3); // pointer version 45 | ReadData(*s4); // reference version 46 | 47 | Print(s1); // ref version 48 | Print(&s2); // pointer version 49 | Print(s3); // pointer version 50 | Print(*s4); // reference version 51 | 52 | return 0; 53 | } 54 | 55 | void Print(const Student *s) 56 | { 57 | cout << "void Print(const Student *)" << endl; 58 | cout << s->firstName << " " << s->lastName << " is taking " << s->course; 59 | cout << " and has a gpa of " << std::setprecision(3) << s->gpa << endl; 60 | } 61 | 62 | void Print(const Student &s) 63 | { 64 | cout << "void Print(const Student &)" << endl; 65 | cout << s.firstName << " " << s.lastName << " is taking " << s.course; 66 | cout << " and has a gpa of " << std::setprecision(3) << s.gpa << endl; 67 | } 68 | 69 | void ReadData(Student *s) 70 | { 71 | cout << "void ReadData(Student *)" << endl; 72 | cout << "Please enter : "; 73 | cin >> s->firstName >> s->lastName; 74 | cout << "Please enter " << s->firstName << " " << s->lastName; 75 | cout << "'s and : "; 76 | cin >> s->gpa >> s->course; 77 | } 78 | 79 | void ReadData(Student &s) 80 | { 81 | cout << "void ReadData(Student &)" << endl; 82 | cout << "Please enter : "; 83 | cin >> s.firstName >> s.lastName; 84 | cout << "Please enter " << s.firstName << " " << s.lastName; 85 | cout << "'s and : "; 86 | cin >> s.gpa >> s.course; 87 | } 88 | 89 | -------------------------------------------------------------------------------- /Chapter04/Assessments/ReadMeChp4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter04/Assessments/ReadMeChp4.pdf -------------------------------------------------------------------------------- /Chapter04/Chp4-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates references to objects 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | int main() 10 | { 11 | int x = 10; 12 | int *p = new int; 13 | 14 | *p = 20; 15 | 16 | // References must be initialized to the object they are referencing 17 | // and may never be assigned another object to reference. 18 | // The reference and the referenced object must be the same type. 19 | int &refInt1 = x; // reference to an integer 20 | int &refInt2 = *p; // also a reference to an integer 21 | 22 | cout << x << " " << *p << " " << refInt1 << " " << refInt2 << endl; 23 | 24 | x++; // updates x and refInt1 25 | (*p)++; // updates *p and refInt2 26 | 27 | cout << x << " " << *p << " " << refInt1 << " " << refInt2 << endl; 28 | 29 | refInt1++; // updates refInt1 and x 30 | refInt2++; // updates refInt2 and *p 31 | 32 | cout << x << " " << *p << " " << refInt1 << " " << refInt2 << endl; 33 | 34 | delete p; 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Chapter04/Chp4-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates references to user defined types 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | using std::string; 9 | 10 | class Student // very simple class -- we'll add to it in the next chapter 11 | { 12 | public: 13 | string name; 14 | float gpa; 15 | }; 16 | 17 | int main() 18 | { 19 | Student s1; 20 | Student &sRef = s1; 21 | s1.name = "Katje Katz"; 22 | s1.gpa = 3.75; 23 | cout << s1.name << " has GPA: " << s1.gpa << endl; 24 | cout << sRef.name << " has GPA: " << sRef.gpa << endl; 25 | 26 | sRef.name = "George Katz"; 27 | sRef.gpa = 3.25; 28 | cout << s1.name << " has GPA: " << s1.gpa << endl; 29 | cout << sRef.name << " has GPA: " << sRef.gpa << endl; 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Chapter04/Chp4-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: Illustrates the difference between function arguments 3 | // which are pointers and those which are references 4 | 5 | #include 6 | 7 | using std::cout; // preferred to: using namespace std; 8 | using std::flush; 9 | 10 | void AddOne(int &); 11 | void AddOne(int *); 12 | void Display(int &); 13 | 14 | int main() 15 | { 16 | int x = 10, *y = nullptr; 17 | y = new int; 18 | *y = 15; 19 | Display(x); 20 | Display(*y); 21 | 22 | AddOne(x); // calls reference version 23 | AddOne(*y); 24 | Display(x); 25 | Display(*y); 26 | 27 | AddOne(&x); // calls pointer version 28 | AddOne(y); 29 | Display(x); 30 | Display(*y); 31 | 32 | delete y; 33 | 34 | return 0; 35 | } 36 | 37 | void AddOne(int &arg) 38 | { 39 | arg++; 40 | } 41 | 42 | void AddOne(int *arg) 43 | { 44 | (*arg)++; 45 | } 46 | 47 | void Display(int &arg) 48 | { 49 | cout << arg << " " << flush; 50 | } 51 | -------------------------------------------------------------------------------- /Chapter04/Chp4-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates a reference as a return type from a function 3 | // Note: This is certainly not a typical use, but demonstrates a reference as a return type from a function. 4 | // (we will see this most heavily used with operator overloading so that operators can be cascaded in usage -- 5 | // this is actually the original motivating reason references were added, long ago, to C++). 6 | 7 | #include 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | 11 | int &CreateId(); // function prototype 12 | 13 | int main() 14 | { 15 | int &id1 = CreateId(); // reference established 16 | int &id2= CreateId(); 17 | cout << "Id1: " << id1 << " Id2: " << id2 << endl; 18 | delete &id1; // Here, '&' is address-of not reference 19 | delete &id2; // It is very unusual we'd delete in this fashion, but now you know you can take the address of a ref variable 20 | // Also, allocating and deleting in diff scopes can lead to errors. This will motivate use of smart pointers later 21 | return 0; 22 | } 23 | 24 | // Remember, it is not typical or recommended to allocate heap memory within a function and return it using a reference. 25 | // The goal here is to demonstrate syntactically how it is done (with the return by reference) and how the subsequent deletion is done (in main) 26 | int &CreateId() 27 | { 28 | static int count = 100; // initialize with first id 29 | int *memory = new int; 30 | *memory = count++; // use count as id, then increment 31 | return *memory; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Chapter04/Chp4-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates a reference to a const object 3 | 4 | #include 5 | using std::cout; // preferred to: using namespace std; 6 | using std::endl; 7 | 8 | int main() 9 | { 10 | int x = 5; 11 | const int &refInt = x; 12 | cout << x << " " << refInt << endl; 13 | // refInt = 6; // illegal. We can't change value of refInt 14 | x = 7; 15 | cout << x << " " << refInt << endl; 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Chapter04/Chp4-Ex6.cpp: -------------------------------------------------------------------------------- 1 | // Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates use of using a reference to a constant object 3 | // as an argument to a function 4 | 5 | #include 6 | 7 | using std::cout; // preferred to: using namespace std; 8 | using std::cin; 9 | using std::endl; 10 | 11 | 12 | struct collection 13 | { 14 | int x; // don't worry, we'll soon see (Chp 5) how to initialize struct or class members easily 15 | float y; 16 | }; 17 | 18 | void Update(collection &); 19 | void Print(const collection &); 20 | 21 | int main() 22 | { 23 | collection collect1, *collect2 = nullptr; 24 | 25 | // allocate memory for collect2 from the heap 26 | collect2 = new collection; 27 | 28 | Update(collect1); // a reference to the object is passes 29 | Update(*collect2); // same here because *collect2 is also an object 30 | 31 | Print(collect1); 32 | Print(*collect2); 33 | 34 | // delete collection pointed to by collect2 35 | delete collect2; 36 | 37 | return 0; 38 | } 39 | 40 | void Update(collection &c) 41 | { 42 | cout << "Enter and members: "; 43 | cin >> c.x >> c.y; 44 | } 45 | 46 | void Print(const collection &c) 47 | { 48 | cout << "x member: " << c.x << " y member: " << c.y << endl; 49 | } 50 | 51 | -------------------------------------------------------------------------------- /Chapter04/Chp4-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a reference to a pointer to data 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | int main() 10 | { 11 | int *ptr = new int; 12 | *ptr = 20; 13 | int *&refPtr = ptr; // establish a reference to a pointer 14 | cout << *ptr << " " << *refPtr << endl; 15 | delete ptr; 16 | 17 | return 0; 18 | } 19 | 20 | -------------------------------------------------------------------------------- /Chapter04/ReadMe: -------------------------------------------------------------------------------- 1 | This directory contains the full program examples which accompany Chapter 4. 2 | -------------------------------------------------------------------------------- /Chapter04/original/Chp4-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates references to objects 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int x = 10; 11 | int *p = new int; 12 | 13 | *p = 20; 14 | 15 | // References must be initialized to the object they are referencing 16 | // and may never be assigned another object to reference. 17 | // The reference and the referenced object must be the same type. 18 | int &refInt1 = x; // reference to an integer 19 | int &refInt2 = *p; // also a reference to an integer 20 | 21 | cout << x << " " << *p << " " << refInt1 << " " << refInt2 << endl; 22 | 23 | x++; // updates x and refInt1 24 | (*p)++; // updates *p and refInt2 25 | 26 | cout << x << " " << *p << " " << refInt1 << " " << refInt2 << endl; 27 | 28 | refInt1++; // updates refInt1 and x 29 | refInt2++; // updates refInt2 and *p 30 | 31 | cout << x << " " << *p << " " << refInt1 << " " << refInt2 << endl; 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Chapter04/original/Chp4-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates references to user defined types 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Student 10 | { 11 | public: 12 | char name[20]; 13 | float gpa; 14 | }; 15 | 16 | int main() 17 | { 18 | Student s1; 19 | Student &sRef = s1; 20 | strcpy(s1.name, "Katje Katz"); 21 | s1.gpa = 3.75; 22 | cout << s1.name << " has GPA: " << s1.gpa << endl; 23 | cout << sRef.name << " has GPA: " << sRef.gpa << endl; 24 | 25 | strcpy(sRef.name, "George Katz"); 26 | sRef.gpa = 3.25; 27 | cout << s1.name << " has GPA: " << s1.gpa << endl; 28 | cout << sRef.name << " has GPA: " << sRef.gpa << endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Chapter04/original/Chp4-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: Illustrates the difference between function arguments 3 | // which are pointers and those which are references 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | void AddOne(int &); 10 | void AddOne(int *); 11 | void Display(int &); 12 | 13 | int main() 14 | { 15 | int x = 10, *y; 16 | y = new int; 17 | *y = 15; 18 | Display(x); 19 | Display(*y); 20 | 21 | AddOne(x); // calls reference version 22 | AddOne(*y); 23 | Display(x); 24 | Display(*y); 25 | 26 | AddOne(&x); // calls pointer version 27 | AddOne(y); 28 | Display(x); 29 | Display(*y); 30 | 31 | return 0; 32 | } 33 | 34 | void AddOne(int &arg) 35 | { 36 | arg++; 37 | } 38 | 39 | void AddOne(int *arg) 40 | { 41 | (*arg)++; 42 | } 43 | 44 | void Display(int &arg) 45 | { 46 | cout << arg << " " << flush; 47 | } 48 | -------------------------------------------------------------------------------- /Chapter04/original/Chp4-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates a reference as a return type from a function 3 | 4 | #include 5 | using namespace std; 6 | 7 | int &CreateId(); // function prototype 8 | 9 | int main() 10 | { 11 | int &id1 = CreateId(); // reference established 12 | int &id2= CreateId(); 13 | cout << "Id1: " << id1 << " Id2: " << id2 << endl; 14 | delete &id1; // Here, '&' is address-of not reference 15 | delete &id2; 16 | 17 | return 0; 18 | } 19 | 20 | int &CreateId() 21 | { 22 | static int count = 100; // initialize with first id 23 | int *memory = new int; 24 | *memory = count++; // use count as id, then increment 25 | return *memory; 26 | } 27 | -------------------------------------------------------------------------------- /Chapter04/original/Chp4-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates a reference to a const object 3 | 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | int x = 5; 10 | const int &refInt = x; 11 | cout << x << " " << refInt << endl; 12 | // refInt = 6; // illegal. We can't change value of refInt 13 | x = 7; 14 | cout << x << " " << refInt << endl; 15 | 16 | return 0; 17 | } 18 | 19 | -------------------------------------------------------------------------------- /Chapter04/original/Chp4-Ex6.cpp: -------------------------------------------------------------------------------- 1 | // Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Illustrates use of using a reference to a constant object 3 | // as an argument to a function 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Collection 11 | { 12 | public: 13 | int x; 14 | float y; 15 | }; 16 | 17 | void Update(Collection *); 18 | void Print(const Collection &); 19 | 20 | int main() 21 | { 22 | Collection collect1, *collect2; 23 | 24 | // allocate memory for collect2 from the heap 25 | collect2 = new Collection; 26 | 27 | Update(&collect1); 28 | Update(collect2); 29 | 30 | Print(collect1); 31 | Print(*collect2); 32 | 33 | // delete collection pointed to by collect2 34 | delete collect2; 35 | 36 | return 0; 37 | } 38 | 39 | void Update(Collection *c) 40 | { 41 | cout << "Enter x and y members: "; 42 | cin >> c->x >> c->y; 43 | } 44 | 45 | void Print(const Collection &c) 46 | { 47 | cout << "x member: " << c.x << " y member: " << c.y << endl; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Chapter04/original/Chp4-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a reference to a pointer to data 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int *ptr = new int; 11 | *ptr = 20; 12 | int *&refPtr = ptr; // establish a reference to a pointer 13 | cout << *ptr << " " << *refPtr << endl; 14 | 15 | return 0; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Chapter04/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter05/Assessments/ReadMeChp5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter05/Assessments/ReadMeChp5.pdf -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To demonstrate a class and struct with simple member functions 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | using std::string; 9 | 10 | struct student 11 | { 12 | string name; 13 | float gpa; 14 | void Initialize(string, float); // function prototype 15 | void Print(); 16 | }; 17 | 18 | class University 19 | { 20 | public: 21 | string name; 22 | int numStudents; 23 | void Initialize(string, int); // function prototype 24 | void Print(); 25 | }; 26 | 27 | void student::Initialize(string n, float avg) 28 | { 29 | name = n; // we'll see how to initialize this, rather than use assignment, later in this chapter 30 | gpa = avg; 31 | } 32 | 33 | void student::Print() 34 | { 35 | cout << name << " GPA: " << gpa << endl; 36 | } 37 | 38 | void University::Initialize(string n, int num) 39 | { 40 | name = n; 41 | numStudents = num; 42 | } 43 | 44 | void University::Print() 45 | { 46 | cout << name << " Enrollment: " << numStudents << endl; 47 | } 48 | 49 | int main() 50 | { 51 | student s1; // instantiate a student (struct instance) 52 | s1.Initialize("Gabby Doone", 4.4); 53 | s1.Print(); 54 | 55 | University u1; // instantiate a University (class) 56 | u1.Initialize("GWU", 25600); 57 | u1.Print(); 58 | 59 | University *u2; // pointer declaration 60 | u2 = new University(); // instantiation with new() 61 | u2->Initialize("UMD", 40500); 62 | u2->Print(); // or alternatively: (*u2).Print(); 63 | delete u2; 64 | 65 | return 0; 66 | } 67 | 68 | -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex10.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate const member functions. 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | using std::string; 9 | 10 | class Student 11 | { 12 | private: 13 | // data members 14 | string firstName; 15 | string lastName; 16 | char middleInitial; 17 | float gpa; 18 | string currentCourse; 19 | const int studentId; // constant data member 20 | public: 21 | // member function prototypes 22 | Student(); // default constructor 23 | Student(const string &, const string &, char, float, const string &, int); 24 | Student(const Student &); // copy constructor 25 | ~Student(); // destructor 26 | void Print() const; // most of these member functions are const 27 | const string &GetFirstName() const { return firstName; } 28 | const string &GetLastName() const { return lastName; } 29 | char GetMiddleInitial() const { return middleInitial; } 30 | float GetGpa() const { return gpa; } 31 | const string &GetCurrentCourse() const { return currentCourse; } 32 | int GetStudentId() const { return studentId; } 33 | void SetCurrentCourse(const string &); // prototype only 34 | }; 35 | 36 | inline void Student::SetCurrentCourse(const string &c) 37 | { 38 | currentCourse = c; // the implementation using the string is far simplier 39 | } 40 | 41 | 42 | // default constructor 43 | Student::Student() : middleInitial('\0'), gpa(0.0), studentId(0) 44 | { 45 | // note: you may still initialize data members here, but using member initialization list is more efficient 46 | // Because string data members, firstName, lastName, currentCourse are initialized with empty strings (they are member objects 47 | // which are default constructed), we do not need to include the default constructor specification for these members above. 48 | } 49 | 50 | // alternate constructor 51 | Student::Student(const string &fn, const string &ln, char mi, float avg, const string &course, int id) : 52 | firstName(fn), lastName(ln), middleInitial(mi), gpa(avg), currentCourse(course), studentId (id) 53 | { 54 | // note: for string data members, the above initialization is calling the constructor matching the signature of item in ()'s 55 | // this is inevitably more efficient than default constructing the data member and then assigning it with a new value in the method body 56 | // note: any pointer data members often need to be set within body of function (but can sometimes be set in init. list too) 57 | } 58 | 59 | // copy constructor 60 | Student::Student(const Student &s) : firstName(s.firstName), lastName(s.lastName), middleInitial(s.middleInitial), 61 | gpa(s.gpa), currentCourse(s.currentCourse), studentId (s.studentId) 62 | { 63 | // remember to do a deep copy for any data members that are pointers 64 | } 65 | 66 | Student::~Student() 67 | { 68 | // remember to delete memory for any data members that are pointers 69 | } 70 | 71 | 72 | void Student::Print() const 73 | { 74 | cout << firstName << " " << middleInitial << ". "; 75 | cout << lastName << " with id: " << studentId; 76 | cout << " and gpa: " << gpa << " is enrolled in: "; 77 | cout << currentCourse << endl; 78 | } 79 | 80 | int main() 81 | { 82 | Student s1("Zack", "Moon", 'R', 3.85, "C++", 1378); 83 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 84 | cout << " Enrolled in " << s1.GetCurrentCourse() << endl; 85 | s1.SetCurrentCourse("Advanced C++ Programming"); 86 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 87 | cout << " New course: " << s1.GetCurrentCourse() << endl; 88 | 89 | const Student s2("Gabby", "Doone", 'A', 3.9, "C++", 2239); 90 | s2.Print(); 91 | // Not allowed, s2 is const 92 | // s2.SetCurrentCourse("Advanced C++ Programming"); 93 | 94 | return 0; 95 | } 96 | 97 | -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate the 'this' pointer 3 | 4 | #include 5 | #include // though we'll prefer std::string, we will need to illustrate one dynamically allocated 6 | // data member to show several important concepts in this chapter (so we'll use a single char *) 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::string; 11 | 12 | class Student 13 | { 14 | public: // for now, let's put everything public access region 15 | string firstName; // data members 16 | string lastName; 17 | char middleInitial; 18 | float gpa; 19 | char *currentCourse; // though we'll prefer std::string, this data member will help us illustrate a few important ideas 20 | // member function prototypes 21 | void Initialize(string, string, char, float, const char *); 22 | void Print(); 23 | }; 24 | 25 | // Member function definition 26 | void Student::Initialize(string fn, string ln, char mi, float gpa, const char *course) 27 | { 28 | firstName = fn; 29 | lastName = ln; 30 | this->middleInitial = mi; // optional use of this 31 | this->gpa = gpa; // required, explicit use of this 32 | currentCourse = new char [strlen(course) + 1]; // remember to allocate the memory for data members that are pointers 33 | strcpy(currentCourse, course); 34 | } 35 | // It is as if Student::Initialize() is written as: 36 | // void Student_Initialize_string_string_char_float_constchar* 37 | // (Student *const this, string fn, string ln, 38 | // char mi, float avg, const char *course) 39 | // { 40 | // this->firstName = fn; 41 | // this->lastName = ln; 42 | // this->middleInitial = mi; 43 | // this->gpa = avg; 44 | // this->currentCourse = new char [strlen(course) + 1]; 45 | // strcpy(this->currentCourse, course); 46 | // } 47 | 48 | // Member function definition 49 | void Student::Print() 50 | { 51 | cout << firstName << " "; 52 | cout << middleInitial << ". "; 53 | cout << lastName << " has a gpa of: "; 54 | cout << gpa << " and is enrolled in: "; 55 | cout << currentCourse << endl; 56 | } 57 | // It is as if Student::Print() is written as: 58 | // void Student_Print(Student *const this) 59 | // { 60 | // cout << this->firstName << " "; 61 | // cout << this->middleInitial << ". " 62 | // cout << this->lastName << " has a gpa of: "; 63 | // cout << this->gpa << " and is enrolled in: "; 64 | // cout << this->currentCourse << endl; 65 | // } 66 | 67 | int main() 68 | { 69 | Student s1; // instance 70 | Student *s2 = new Student; // ptr to an instance 71 | 72 | s1.Initialize("Mary", "Jacobs", 'I', 3.9, "C++"); 73 | s2->Initialize("Sam", "Nelson", 'B', 3.2, "C++"); 74 | s1.Print(); 75 | s2->Print(); 76 | 77 | delete [] s1.currentCourse; // delete dynamically allocated data members 78 | delete [] s2->currentCourse; 79 | delete s2; // delete dynamically allocated instance 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To examine access regions. 3 | 4 | #include 5 | #include // though we'll prefer std::string, we will need to illustrate one dynamically allocated 6 | // data member to show several important concepts in this chapter (so we'll use a single char *) 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::string; 11 | 12 | class Student 13 | { 14 | // private members are accessible only within the scope of 15 | // the class (e.g. within member functions or friends) 16 | private: 17 | string firstName; // data members 18 | string lastName; 19 | char middleInitial; 20 | float gpa; 21 | char *currentCourse; // though we'll prefer std::string, this data member will help us illustrate a few important ideas 22 | // public members are accessible from any scope 23 | public: 24 | // member function prototypes 25 | void Initialize(); 26 | void Initialize(string, string, char, float, const char *); 27 | void CleanUp(); 28 | void Print(); 29 | }; 30 | 31 | void Student::Initialize() 32 | { 33 | // even though string data members, firstName and lastName, are initialized with empty strings (string is a class and does so for us), 34 | // we're showing here how to clear the string, as it may be re-initialized more than once 35 | firstName.clear(); 36 | lastName.clear(); 37 | middleInitial = '\0'; // null character 38 | gpa = 0.0; 39 | currentCourse = nullptr; 40 | } 41 | 42 | // Overloaded member function definition 43 | void Student::Initialize(string fn, string ln, char mi, float avg, const char *course) 44 | { 45 | firstName = fn; 46 | lastName = ln; 47 | middleInitial = mi; 48 | gpa = avg; 49 | currentCourse = new char [strlen(course) + 1]; // remember to dynamically allocate the memory for data members that are pointers 50 | strcpy(currentCourse, course); 51 | } 52 | 53 | // Member function definition 54 | void Student::CleanUp() 55 | { 56 | delete [] currentCourse; // deallocate the memory for data members that are pointers 57 | } 58 | 59 | // Member function definition 60 | void Student::Print() 61 | { 62 | cout << firstName << " " << middleInitial << ". "; 63 | cout << lastName << " has gpa: " << gpa; 64 | cout << " and enrolled in: " << currentCourse << endl; 65 | } 66 | 67 | int main() 68 | { 69 | Student s1; 70 | 71 | // Initialize() is public; accessible from any scope 72 | s1.Initialize("Ming", "Li", 'I', 3.9, "C++"); 73 | 74 | s1.Print(); // Print() is public, accessible from main() 75 | 76 | // Error! firstName is private; not accessible in main() 77 | // cout << s1.firstName << endl; 78 | 79 | // CleanUp() is public, accessible from any scope 80 | s1.CleanUp(); 81 | 82 | return 0; 83 | } 84 | 85 | -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (C) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To understand constructor basics. 3 | 4 | #include 5 | 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | using std::string; 9 | 10 | class University 11 | { 12 | private: 13 | string name; 14 | int numStudents; 15 | public: 16 | // constructor prototypes 17 | University(); // default constructor 18 | University(const string &, int); 19 | void Print(); 20 | void CleanUp(); 21 | }; 22 | 23 | University::University() // default, no-argument constructor 24 | { 25 | // Because a string is a class type, all strings are constructed with an empty value by default. 26 | // For that reason, we do not need to explicitly initialize strings if an empty string is desired. 27 | // We’ll see a preferred manner of initialization for all data members shortly in this chapter. 28 | // Hence, name is constructed by default (empty string) 29 | numStudents = 0; 30 | } 31 | 32 | University::University(const string &n, int num) // alternate constructor 33 | { 34 | // any pointer data members would need to be allocated here 35 | name = n; // not to worry, assignment with strings will do a deep assignment 36 | numStudents = num; 37 | } 38 | 39 | void University::Print() 40 | { 41 | cout << "University: " << name; 42 | cout << " Enrollment: " << numStudents << endl; 43 | } 44 | 45 | void University::CleanUp() 46 | { 47 | // any pointer data members would need to be deallocated here 48 | } 49 | 50 | int main() 51 | { 52 | University u1; // Implicit call to default constructor 53 | University u2("University of Delaware", 23800); // uses alternate constructor 54 | University u3{"Temple University", 20500}; // also uses alternate constructor - note use of {}'s 55 | u1.Print(); 56 | u2.Print(); 57 | u3.Print(); 58 | u1.CleanUp(); 59 | u2.CleanUp(); 60 | u3.CleanUp(); 61 | 62 | return 0; 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To understand the copy constructor. 3 | 4 | #include 5 | #include // though we'll prefer std::string, we will need to illustrate one dynamically allocated 6 | // data member to show several important concepts in this chapter (so we'll use a single char *) 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::string; 11 | 12 | class Student 13 | { 14 | private: 15 | // data members 16 | string firstName; 17 | string lastName; 18 | char middleInitial; 19 | float gpa; 20 | char *currentCourse; // though we'll prefer std::string, this data member will help us illustrate a few important ideas 21 | public: 22 | // member function prototypes 23 | Student(); // default constructor 24 | Student(const string &, const string &, char, float, const char *); 25 | Student(const Student &); // copy constructor prototype 26 | void CleanUp(); 27 | void Print(); 28 | void SetFirstName(const string &); 29 | }; 30 | 31 | // default constructor 32 | Student::Student() 33 | { 34 | // Remember, firstName and lastName are member objects of type string; they are default constructed and hence 35 | // 'empty' by default. They HAVE been initialized. 36 | middleInitial = '\0'; 37 | gpa = 0.0; 38 | currentCourse = nullptr; 39 | } 40 | 41 | // Alternate constructor member function definition 42 | Student::Student(const string &fn, const string &ln, char mi, float avg, const char *course) 43 | { 44 | firstName = fn; 45 | lastName = ln; 46 | middleInitial = mi; 47 | gpa = avg; 48 | currentCourse = new char [strlen(course) + 1]; // // remember to dynamically allocate the memory for data members that are pointers 49 | strcpy(currentCourse, course); 50 | } 51 | 52 | // Copy constructor definition - implements a deep copy 53 | Student::Student(const Student &s) 54 | { 55 | firstName = s.firstName; // string will do a deep assignment for us 56 | lastName = s.lastName; 57 | middleInitial = s.middleInitial; 58 | gpa = s.gpa; 59 | // for ptr data member -- allocate necessary memory for destination string 60 | currentCourse = new char [strlen(s.currentCourse) + 1]; 61 | // then copy source to destination string 62 | strcpy(currentCourse, s.currentCourse); 63 | } 64 | 65 | // Member function definition 66 | void Student::CleanUp() 67 | { 68 | delete [] currentCourse; // deallocate the memory for data members that are pointers 69 | } 70 | 71 | // Member function definition 72 | void Student::Print() 73 | { 74 | cout << firstName << " " << middleInitial << ". "; 75 | cout << lastName << " has a gpa of: " << gpa; 76 | cout << " and is enrolled in: " << currentCourse << endl; 77 | } 78 | 79 | void Student::SetFirstName(const string &fn) 80 | { 81 | firstName = fn; 82 | } 83 | 84 | int main() 85 | { 86 | // instantiate two Students 87 | Student s1("Zachary", "Moon", 'R', 3.7, "C++"); 88 | Student s2("Gabrielle", "Doone", 'A', 3.7, "C++"); 89 | 90 | // These initializations implicitly invoke copy constructor 91 | Student s3(s1); 92 | Student s4 = s2; 93 | s3.SetFirstName("Zack"); // alter each object slightly 94 | s4.SetFirstName("Gabby"); 95 | 96 | // This sequence does not invoke copy constructor 97 | // This is instead an assignment. 98 | // Student s5("Giselle", "LeBrun", 'A', 3.1, "C++); 99 | // Student s6; 100 | // s6 = s5; // this is an assignment, not initialization 101 | 102 | s1.Print(); // print each instance 103 | s3.Print(); 104 | s2.Print(); 105 | s4.Print(); 106 | 107 | s1.CleanUp(); // Since some data members are pointers, 108 | s2.CleanUp(); // lets call CleanUp() to delete() them 109 | s3.CleanUp(); 110 | s4.CleanUp(); 111 | 112 | return 0; 113 | } 114 | -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a class destructor. 3 | 4 | #include 5 | #include // though we'll prefer std::string, we will need to illustrate one dynamically allocated 6 | // data member to show several important concepts in this chapter (so we'll use a single char *) 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::string; 11 | 12 | class University 13 | { 14 | private: 15 | char *name; // though we'll prefer std::string, this data member will help us illustrate destructor purpose 16 | int numStudents; 17 | public: 18 | // constructor prototypes 19 | University(); // default constructor 20 | University(const char *, int); // alternate constructor 21 | University(const University &); // copy constructor 22 | ~University(); // destructor prototype 23 | void Print(); 24 | }; 25 | 26 | University::University() // default constructor 27 | { 28 | name = nullptr; 29 | numStudents = 0; 30 | } 31 | 32 | University::University(const char * n, int num) // alt constructor 33 | { 34 | name = new char [strlen(n) + 1]; // allocate memory for ptr data members 35 | strcpy(name, n); 36 | numStudents = num; 37 | } 38 | 39 | University::University(const University &u) // copy const 40 | { 41 | name = new char [strlen(u.name) + 1]; // deep copy data members that are pointers 42 | strcpy(name, u.name); 43 | numStudents = u.numStudents; 44 | } 45 | 46 | University::~University() // destructor definition 47 | { 48 | delete [] name; // be sure to deallocate any dynamically allocoated memory 49 | cout << "Destructor called " << this << endl; 50 | } 51 | 52 | void University::Print() 53 | { 54 | cout << "University: " << name; 55 | cout << " Enrollment: " << numStudents << endl; 56 | } 57 | 58 | int main() 59 | { 60 | University u1("Temple University", 39500); 61 | University *u2 = new University("Boston U", 32500); 62 | u1.Print(); 63 | u2->Print(); 64 | delete u2; // destructor will be called before delete() 65 | // destructor for u1 will be called before 66 | return 0; // program completes 67 | } 68 | 69 | -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex8.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate inline functions. 3 | 4 | #include 5 | #include // though we'll prefer std::string, we will need to illustrate one dynamically allocated 6 | // data member to show several important concepts in this chapter (so we'll use a single char *) 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::string; 11 | 12 | class Student 13 | { 14 | private: 15 | // data members 16 | string firstName; 17 | string lastName; 18 | char middleInitial; 19 | float gpa; 20 | char *currentCourse; // though we'll prefer std::string, this data member will help us illustrate a few important ideas 21 | public: 22 | // member function prototypes 23 | Student(); // default constructor 24 | Student(const string &, const string &, char, float, const char *); 25 | Student(const Student &); // copy constructor 26 | ~Student(); // destructor 27 | void Print(); 28 | 29 | // inline function definitions 30 | // firstName is returned as a const string 31 | const string &GetFirstName() { return firstName; } 32 | const string &GetLastName() { return lastName; } 33 | char GetMiddleInitial() { return middleInitial; } 34 | float GetGpa() { return gpa; } 35 | const char *GetCurrentCourse() { return currentCourse; } // we'll contrast this access fn to the other Get fns -- see book discussion 36 | 37 | // prototype only, see inline function definiton below 38 | void SetCurrentCourse(const char *); 39 | }; 40 | 41 | inline void Student::SetCurrentCourse(const char *c) 42 | { 43 | delete [] currentCourse; // delete existing course 44 | currentCourse = new char [strlen(c) + 1]; // copy in new one 45 | strcpy(currentCourse, c); 46 | } 47 | 48 | // Definitions for default, alternate, copy constructor 49 | 50 | // default constructor 51 | Student::Student() 52 | { 53 | // string data members, firstName and lastName, are initialized with empty strings (string is a class and does so for us) 54 | // because they are member objects (and are default constructed) 55 | middleInitial = '\0'; 56 | gpa = 0.0; 57 | currentCourse = nullptr; 58 | } 59 | 60 | // Alternate constructor member function definition 61 | Student::Student(const string &fn, const string &ln, char mi, float avg, const char *course) 62 | { 63 | firstName = fn; 64 | lastName = ln; 65 | middleInitial = mi; 66 | gpa = avg; 67 | // remember to allocate memory for the pointer data members 68 | currentCourse = new char [strlen(course) + 1]; 69 | strcpy(currentCourse, course); 70 | } 71 | 72 | // Copy constructor definition -implement a deep copy 73 | Student::Student(const Student &s) 74 | { 75 | firstName = s.firstName; 76 | lastName = s.lastName; 77 | middleInitial = s.middleInitial; 78 | gpa = s.gpa; 79 | // for ptr data members - allocate necessary memory for destination string 80 | currentCourse = new char [strlen(s.currentCourse) + 1]; 81 | // then copy source to destination string 82 | strcpy(currentCourse, s.currentCourse); 83 | } 84 | 85 | // Member function definition 86 | Student::~Student() 87 | { 88 | delete [] currentCourse; 89 | } 90 | 91 | // Member function definition 92 | void Student::Print() 93 | { 94 | cout << firstName << " " << middleInitial << ". "; 95 | cout << lastName << " has a gpa of: " << gpa; 96 | cout << " and is enrolled in: " << currentCourse << endl; 97 | } 98 | 99 | 100 | int main() 101 | { 102 | Student s1("Jo", "Muritz", 'Z', 4.0, "C++"); 103 | 104 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 105 | cout << " Enrolled in: " << s1.GetCurrentCourse() << endl; 106 | 107 | s1.SetCurrentCourse("Advanced C++ Programming"); 108 | 109 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 110 | cout << " New course: " << s1.GetCurrentCourse() << endl; 111 | 112 | return 0; 113 | } 114 | 115 | -------------------------------------------------------------------------------- /Chapter05/Chp5-Ex9.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To understand const data members and the member initialization list 3 | // Note: The constructor member initialization list was originally created to provide a manner to initialize data members 4 | // that are const or references. However, it can additionally (and preferably) be used as an efficient way to fully initialize 5 | // virtually any data member. 6 | 7 | #include 8 | 9 | using std::cout; // preferred to: using namespace std; 10 | using std::endl; 11 | using std::string; 12 | 13 | class Student 14 | { 15 | private: 16 | // data members 17 | string firstName; 18 | string lastName; 19 | char middleInitial; 20 | float gpa; 21 | string currentCourse; // let's finally convert this to a std::string -- we've illustrated most ptr special needs within classes by now 22 | const int studentId; // constant data member 23 | public: 24 | // member function prototypes 25 | Student(); // default constructor 26 | Student(const string &, const string &, char, float, const string &, int); 27 | Student(const Student &); // copy constructor 28 | ~Student(); // destructor 29 | void Print(); 30 | const string &GetFirstName() { return firstName; } 31 | const string &GetLastName() { return lastName; } 32 | char GetMiddleInitial() { return middleInitial; } 33 | float GetGpa() { return gpa; } 34 | const string &GetCurrentCourse() { return currentCourse; } 35 | void SetCurrentCourse(const string &); // prototype only 36 | }; 37 | 38 | inline void Student::SetCurrentCourse(const string &c) 39 | { 40 | currentCourse = c; // the implementation using the string is far simplier 41 | } 42 | 43 | 44 | // Member init. list is used to set data members 45 | Student::Student() : firstName(), lastName(), middleInitial('\0'), gpa(0.0), currentCourse(), studentId(0) 46 | { 47 | // You may still set data members here, but using above initialization is more efficient than using assignment 48 | // Note: firstName, lastName, currentCourse are shown in member init. list selecting default constructor for initialization. 49 | // However, as this is the default action for member objects (string), we don’t need to explicitly include 50 | // these members in the member initialization list (nor will we include them in future examples). 51 | 52 | } 53 | 54 | // member init. list is used to set data members 55 | Student::Student(const string &fn, const string &ln, char mi, float avg, const string &course, int id) : 56 | firstName(fn), lastName(ln), middleInitial(mi), gpa(avg), currentCourse(course), studentId (id) 57 | { 58 | // note: for string data members, the above initialization is calling the constructor matching the signature of item in ()'s 59 | // this is inevitably more efficient than default constructing the data member and then assigning it with a new value in the method body 60 | // note: any pointer data members often need to be set within body of function (but can sometimes be set in init. list too) 61 | } 62 | 63 | // member init. list used to set studentId 64 | Student::Student(const Student &s) : firstName(s.firstName), lastName(s.lastName), middleInitial(s.middleInitial), 65 | gpa(s.gpa), currentCourse(s.currentCourse), studentId (s.studentId) 66 | { 67 | // remember to do a deep copy for any data members that are pointers 68 | } 69 | 70 | Student::~Student() 71 | { 72 | // remember to delete memory for any data members that are pointers 73 | } 74 | 75 | void Student::Print() 76 | { 77 | cout << firstName << " " << middleInitial << ". "; 78 | cout << lastName << " with id: " << studentId; 79 | cout << " and gpa: " << gpa << " is enrolled in: "; 80 | cout << currentCourse << endl; 81 | 82 | } 83 | 84 | int main() 85 | { 86 | Student s1("Renee", "Alexander", 'Z', 3.7, "C++", 1290); 87 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 88 | cout << " has gpa of: " << s1.GetGpa() << endl; 89 | 90 | return 0; 91 | } 92 | -------------------------------------------------------------------------------- /Chapter05/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 5. 2 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Purpose: To demonstrate a class and struct with simple member functions 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | struct student 9 | { 10 | char name[20]; 11 | float gpa; 12 | void Initialize(const char *, float); // function prototype 13 | void Print(); 14 | }; 15 | 16 | class University 17 | { 18 | public: 19 | char name[20]; 20 | int numStudents; 21 | void Initialize(const char *, int); // function prototype 22 | void Print(); 23 | }; 24 | 25 | void student::Initialize(const char *n, float avg) 26 | { 27 | strcpy(name, n); 28 | gpa = avg; 29 | } 30 | 31 | void student::Print() 32 | { 33 | cout << name << " GPA: " << gpa << endl; 34 | } 35 | 36 | void University::Initialize(const char *n, int num) 37 | { 38 | strcpy(name, n); 39 | numStudents = num; 40 | } 41 | 42 | void University::Print() 43 | { 44 | cout << name << " Enrollment: " << numStudents << endl; 45 | } 46 | 47 | int main() 48 | { 49 | student s1; // instantiate a student (struct instance) 50 | s1.Initialize("Gabby Doone", 4.4); 51 | s1.Print(); 52 | 53 | University u1; // instantiate a University (class) 54 | u1.Initialize("GWU", 25600); 55 | u1.Print(); 56 | 57 | University *u2; // pointer declaration 58 | u2 = new University(); // instantiation with new() 59 | u2->Initialize("UMD", 40500); 60 | u2->Print(); // or alternatively: (*u2).Print(); 61 | delete u2; 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex10.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate const member functions. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Student 9 | { 10 | private: 11 | // data members 12 | char *firstName; 13 | char *lastName; 14 | char middleInitial; 15 | float gpa; 16 | char *currentCourse; 17 | const int studentId; // constant data member 18 | public: 19 | // member function prototypes 20 | Student(); // default constructor 21 | Student(const char *, const char *, char, float, const char *, int); 22 | Student(const Student &); // copy constructor 23 | ~Student(); // destructor 24 | void Print() const; // most of these member functions are const 25 | const char *GetFirstName() const { return firstName; } 26 | const char *GetLastName() const { return lastName; } 27 | char GetMiddleInitial() const { return middleInitial; } 28 | float GetGpa() const { return gpa; } 29 | const char *GetCurrentCourse() const 30 | { return currentCourse; } 31 | int GetStudentId() const { return studentId; } 32 | void SetCurrentCourse(const char *); // prototype only 33 | }; 34 | 35 | 36 | inline void Student::SetCurrentCourse(const char *c) 37 | { 38 | delete currentCourse; 39 | currentCourse = new char [strlen(c) + 1]; 40 | strcpy(currentCourse, c); 41 | } 42 | 43 | 44 | // Member init. list is used to set studentId and gpa 45 | Student::Student() : studentId(0), gpa(0.0) 46 | { 47 | firstName = lastName = 0; // NULL pointer 48 | middleInitial = '\0'; 49 | currentCourse = 0; 50 | } 51 | 52 | // member init. list is used to set studentId, gpa, and middleInitial 53 | Student::Student(const char *fn, const char *ln, char mi, float avg, 54 | const char *course, int id) : studentId (id), gpa (avg), 55 | middleInitial(mi) 56 | { 57 | firstName = new char [strlen(fn) + 1]; 58 | strcpy(firstName, fn); 59 | lastName = new char [strlen(ln) + 1]; 60 | strcpy(lastName, ln); 61 | currentCourse = new char [strlen(course) + 1]; 62 | strcpy(currentCourse, course); 63 | } 64 | 65 | // member init. list used to set studentId 66 | Student::Student(const Student &s) : studentId (s.studentId) 67 | { 68 | firstName = new char [strlen(s.firstName) + 1]; 69 | strcpy(firstName, s.firstName); 70 | lastName = new char [strlen(s.lastName) + 1]; 71 | strcpy(lastName, s.lastName); 72 | middleInitial = s.middleInitial; 73 | gpa = s.gpa; 74 | currentCourse = new char [strlen(s.currentCourse) + 1]; 75 | strcpy(currentCourse, s.currentCourse); 76 | } 77 | 78 | Student::~Student() 79 | { 80 | delete firstName; 81 | delete lastName; 82 | delete currentCourse; 83 | } 84 | 85 | void Student::Print() const 86 | { 87 | cout << firstName << " " << middleInitial << ". "; 88 | cout << lastName << " with id: " << studentId; 89 | cout << " and gpa: " << gpa << " is enrolled in: "; 90 | cout << currentCourse << endl; 91 | } 92 | 93 | int main() 94 | { 95 | Student s1("Zack", "Moon", 'R', 3.85, "C++", 1378); 96 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 97 | cout << " Enrolled in " << s1.GetCurrentCourse() << endl; 98 | s1.SetCurrentCourse("Advanced C++ Programming"); 99 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 100 | cout << " New course: " << s1.GetCurrentCourse() << endl; 101 | 102 | const Student s2("Gabby", "Doone", 'A', 3.9, "C++", 2239); 103 | s2.Print(); 104 | // Not allowed, s2 is const 105 | // s2.SetCurrentCourse("Advanced C++ Programming"); 106 | 107 | return 0; 108 | } 109 | 110 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate the 'this' pointer 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Student 9 | { 10 | public: // for now, let's put everything public access region 11 | char *firstName; // data members 12 | char *lastName; 13 | char middleInitial; 14 | float gpa; 15 | char *currentCourse; 16 | // member function prototypes 17 | void Initialize(const char *, const char *, char, float, const char *); 18 | void Print(); 19 | }; 20 | 21 | // Member function definition 22 | void Student::Initialize(const char *fn, const char *ln, char mi, 23 | float gpa, const char *course) 24 | { 25 | firstName = new char [strlen(fn) + 1]; 26 | strcpy(firstName, fn); 27 | lastName = new char [strlen(ln) + 1]; 28 | strcpy(lastName, ln); 29 | this->middleInitial = mi; // optional use of this 30 | this->gpa = gpa; // required, explicit use of this 31 | currentCourse = new char [strlen(course) + 1]; 32 | strcpy(currentCourse, course); 33 | } 34 | // It is as if Student::Initialize() is written as: 35 | // void Student_Initialize_constchar*_constchar*_float_constchar* 36 | // (Student *const this, const char *fn, const char *ln, 37 | // char mi, float avg, const char *course) 38 | // { 39 | // this->firstName = new char [strlen(fn) + 1]; 40 | // strcpy(this->firstName, fn); 41 | // this->lastName = new char [strlen(ln) + 1]; 42 | // strcpy(this->lastName, ln); 43 | // this->middleInitial = mi; 44 | // this->gpa = avg; 45 | // this->currentCourse = new char [strlen(course) + 1]; 46 | // strcpy(this->currentCourse, course); 47 | // } 48 | 49 | // Member function definition 50 | void Student::Print() 51 | { 52 | cout << firstName << " "; 53 | cout << middleInitial << ". "; 54 | cout << lastName << " has a gpa of: "; 55 | cout << gpa << " and is enrolled in: "; 56 | cout << currentCourse << endl; 57 | } 58 | // It is as if Student::Print() is written as: 59 | // void Student_Print(Student *const this) 60 | // { 61 | // cout << this->firstName << " "; 62 | // cout << this->middleInitial << ". " 63 | // cout << this->lastName << " has a gpa of: "; 64 | // cout << this->gpa << " and is enrolled in: "; 65 | // cout << this->currentCourse << endl; 66 | // } 67 | 68 | int main() 69 | { 70 | Student s1; // instance 71 | Student *s2 = new Student; // ptr to an instance 72 | 73 | s1.Initialize("Mary", "Jacobs", 'I', 3.9, "C++"); 74 | s2->Initialize("Sam", "Nelson", 'B', 3.2, "C++"); 75 | s1.Print(); 76 | s2->Print(); 77 | 78 | delete s1.firstName; // delete dynamically allocated 79 | delete s1.lastName; // data members 80 | delete s1.currentCourse; 81 | delete s2->firstName; 82 | delete s2->lastName; 83 | delete s2->currentCourse; 84 | delete s2; // delete dynamically allocated instance 85 | 86 | return 0; 87 | } 88 | 89 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To examine access regions. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Student 9 | { 10 | // private members are accessible only within the scope of 11 | // the class (e.g. within member functions or friends) 12 | private: 13 | char *firstName; // data members 14 | char *lastName; 15 | char middleInitial; 16 | float gpa; 17 | char *currentCourse; 18 | char *studentId; 19 | // public members are accessible from any scope 20 | public: 21 | // member function prototypes 22 | void Initialize(); 23 | void Initialize(const char *, const char *, char, float, 24 | const char *, const char *); 25 | void CleanUp(); 26 | void Print(); 27 | }; 28 | 29 | void Student::Initialize() 30 | { 31 | firstName = lastName = 0; // NULL pointer 32 | middleInitial = '\0'; // null character 33 | gpa = 0.0; 34 | currentCourse = studentId = 0; 35 | } 36 | 37 | // Overloaded member function definition 38 | void Student::Initialize(const char *fn, const char *ln, char mi, 39 | float avg, const char *course, const char *id) 40 | { 41 | firstName = new char [strlen(fn) + 1]; 42 | strcpy(firstName, fn); 43 | lastName = new char [strlen(ln) + 1]; 44 | strcpy(lastName, ln); 45 | middleInitial = mi; 46 | gpa = avg; 47 | currentCourse = new char [strlen(course) + 1]; 48 | strcpy(currentCourse, course); 49 | studentId = new char [strlen(id) + 1]; 50 | strcpy (studentId, id); 51 | } 52 | 53 | // Member function definition 54 | void Student::CleanUp() 55 | { 56 | delete firstName; 57 | delete lastName; 58 | delete currentCourse; 59 | delete studentId; 60 | } 61 | 62 | // Member function definition 63 | void Student::Print() 64 | { 65 | cout << firstName << " " << middleInitial << ". "; 66 | cout << lastName << " with id: " << studentId; 67 | cout << " has gpa: " << gpa << " and enrolled in: "; 68 | cout << currentCourse << endl; 69 | } 70 | 71 | int main() 72 | { 73 | Student s1; 74 | 75 | // Initialize() is public; accessible from any scope 76 | s1.Initialize("Ming", "Li", 'I', 3.9, "C++", "178GW"); 77 | 78 | s1.Print(); // Print() is public, accessible from main() 79 | 80 | // Error! firstName is private; not accessible in main() 81 | // cout << s1.firstName << endl; 82 | 83 | // CleanUp() is public, accessible from any scope 84 | s1.CleanUp(); 85 | 86 | return 0; 87 | } 88 | 89 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex4.cpp: -------------------------------------------------------------------------------- 1 | // (C) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To understand constructor basics. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class University 9 | { 10 | private: 11 | char name[30]; 12 | int numStudents; 13 | public: 14 | // constructor prototypes 15 | University(); // default constructor 16 | University(const char *, int); 17 | void Print(); 18 | }; 19 | 20 | University::University() // default, no-argument constructor 21 | { 22 | name[0] = '\0'; 23 | numStudents = 0; 24 | } 25 | 26 | University::University(const char * n, int num) // alternate constructor 27 | { 28 | strcpy(name, n); 29 | numStudents = num; 30 | } 31 | 32 | void University::Print() 33 | { 34 | cout << "University: " << name; 35 | cout << " Enrollment: " << numStudents << endl; 36 | } 37 | 38 | int main() 39 | { 40 | University u1; // Implicit call to default constructor 41 | University u2("University of Delaware", 23800); // uses alternate constructor 42 | u1.Print(); 43 | u2.Print(); 44 | 45 | return 0; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex5.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To understand the copy constructor. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Student 9 | { 10 | private: 11 | // data members 12 | char *firstName; 13 | char *lastName; 14 | char middleInitial; 15 | float gpa; 16 | char *currentCourse; 17 | public: 18 | // member function prototypes 19 | Student(); // default constructor 20 | Student(const char *, const char *, char, float, const char *); 21 | Student(const Student &); // copy constructor prototype 22 | void CleanUp(); 23 | void Print(); 24 | void SetFirstName(const char *); 25 | }; 26 | 27 | // default constructor 28 | Student::Student() 29 | { 30 | firstName = lastName = 0; // NULL pointer 31 | middleInitial = '\0'; 32 | gpa = 0.0; 33 | currentCourse = 0; 34 | } 35 | 36 | // Alternate constructor member function definition 37 | Student::Student(const char *fn, const char *ln, char mi, 38 | float avg, const char *course) 39 | { 40 | firstName = new char [strlen(fn) + 1]; 41 | strcpy(firstName, fn); 42 | lastName = new char [strlen(ln) + 1]; 43 | strcpy(lastName, ln); 44 | middleInitial = mi; 45 | gpa = avg; 46 | currentCourse = new char [strlen(course) + 1]; 47 | strcpy(currentCourse, course); 48 | } 49 | 50 | // Copy constructor definition - implements a deep copy 51 | Student::Student(const Student &s) 52 | { 53 | // allocate necessary memory for destination string 54 | firstName = new char [strlen(s.firstName) + 1]; 55 | // then copy source to destination string 56 | strcpy(firstName, s.firstName); 57 | lastName = new char [strlen(s.lastName) + 1]; 58 | // data members which are not pointers do not need their 59 | // space allocated for deep copy, such as is done above 60 | strcpy(lastName, s.lastName); 61 | middleInitial = s.middleInitial; 62 | gpa = s.gpa; 63 | // allocate destination string space, then copy contents 64 | currentCourse = new char [strlen(s.currentCourse) + 1]; 65 | strcpy(currentCourse, s.currentCourse); 66 | } 67 | 68 | // Member function definition 69 | void Student::CleanUp() 70 | { 71 | delete firstName; 72 | delete lastName; 73 | delete currentCourse; 74 | } 75 | 76 | // Member function definition 77 | void Student::Print() 78 | { 79 | cout << firstName << " " << middleInitial << ". "; 80 | cout << lastName << " has a gpa of: " << gpa; 81 | cout << " and is enrolled in: " << currentCourse << endl; 82 | } 83 | 84 | void Student::SetFirstName(const char *n) 85 | { 86 | delete firstName; // delete existing name 87 | firstName = new char [strlen(n) + 1]; 88 | strcpy(firstName, n); 89 | } 90 | 91 | int main() 92 | { 93 | // instantiate two Students 94 | Student s1("Zachary", "Moon", 'R', 3.7, "C++"); 95 | Student s2("Gabrielle", "Doone", 'A', 3.7, "C++"); 96 | 97 | // These initializations implicitly invoke copy constructor 98 | Student s3(s1); 99 | Student s4 = s2; 100 | s3.SetFirstName("Zack"); // alter each object slightly 101 | s4.SetFirstName("Gabby"); 102 | 103 | // This sequence does not invoke copy constructor 104 | // This is instead an assignment. 105 | // Student s5("Giselle", "LeBrun", 'A', 3.1, "C++); 106 | // Student s6; 107 | // s6 = s5; // this is an assignment, not initialization 108 | 109 | s1.Print(); // print each instance 110 | s3.Print(); 111 | s2.Print(); 112 | s4.Print(); 113 | 114 | s1.CleanUp(); // Since some data members are pointers, 115 | s2.CleanUp(); // lets call a function to delete() them 116 | s3.CleanUp(); 117 | s4.CleanUp(); 118 | 119 | return 0; 120 | } 121 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex7.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a class destructor. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class University 9 | { 10 | private: 11 | char *name; 12 | int numStudents; 13 | public: 14 | // constructor prototypes 15 | University(); // default constructor 16 | University(const char *, int); // alternate constructor 17 | University(const University &); // copy constructor 18 | ~University(); // destructor prototype 19 | void Print(); 20 | }; 21 | 22 | University::University() // default constructor 23 | { 24 | name = 0; // NULL pointer 25 | numStudents = 0; 26 | } 27 | 28 | University::University(const char * n, int num) // alt constructor 29 | { 30 | name = new char [strlen(n) + 1]; 31 | strcpy(name, n); 32 | numStudents = num; 33 | } 34 | 35 | University::University(const University &u) // copy const 36 | { 37 | name = new char [strlen(u.name) + 1]; // deep copy 38 | strcpy(name, u.name); 39 | numStudents = u.numStudents; 40 | } 41 | 42 | University::~University() // destructor definition 43 | { 44 | delete name; 45 | cout << "Destructor called " << this << endl; 46 | } 47 | 48 | void University::Print() 49 | { 50 | cout << "University: " << name; 51 | cout << " Enrollment: " << numStudents << endl; 52 | } 53 | 54 | int main() 55 | { 56 | University u1("Temple University", 39500); 57 | University *u2 = new University("Boston U", 32500); 58 | u1.Print(); 59 | u2->Print(); 60 | delete u2; // destructor will be called before delete() 61 | // destructor for u1 will be called before 62 | return 0; // program completes 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex8.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate inline functions. 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Student 9 | { 10 | private: 11 | // data members 12 | char *firstName; 13 | char *lastName; 14 | char middleInitial; 15 | float gpa; 16 | char *currentCourse; 17 | public: 18 | // member function prototypes 19 | Student(); // default constructor 20 | Student(const char *, const char *, char, float, const char *); 21 | Student(const Student &); // copy constructor 22 | ~Student(); // destructor 23 | void Print(); 24 | 25 | // inline function definitions 26 | // firstName is returned as a const string 27 | const char *GetFirstName() { return firstName; } 28 | const char *GetLastName() { return lastName; } 29 | char GetMiddleInitial() { return middleInitial; } 30 | float GetGpa() { return gpa; } 31 | const char *GetCurrentCourse() { return currentCourse; } 32 | 33 | // prototype only, see inline function definiton below 34 | void SetCurrentCourse(const char *); 35 | }; 36 | 37 | inline void Student::SetCurrentCourse(const char *c) 38 | { 39 | delete currentCourse; 40 | currentCourse = new char [strlen(c) + 1]; 41 | strcpy(currentCourse, c); 42 | } 43 | // Definitions for default, alternate, copy constructor, 44 | // the destructor, and Print() have been omitted for space, 45 | // but are same as last example for class Student 46 | 47 | // default constructor 48 | Student::Student() 49 | { 50 | firstName = lastName = 0; // NULL pointer 51 | middleInitial = '\0'; 52 | gpa = 0.0; 53 | currentCourse = 0; 54 | } 55 | 56 | // Alternate constructor member function definition 57 | Student::Student(const char *fn, const char *ln, char mi, 58 | float avg, const char *course) 59 | { 60 | firstName = new char [strlen(fn) + 1]; 61 | strcpy(firstName, fn); 62 | lastName = new char [strlen(ln) + 1]; 63 | strcpy(lastName, ln); 64 | middleInitial = mi; 65 | gpa = avg; 66 | currentCourse = new char [strlen(course) + 1]; 67 | strcpy(currentCourse, course); 68 | } 69 | 70 | // Copy constructor definition implement a deep copy 71 | Student::Student(const Student &s) 72 | { 73 | // allocate necessary memory for destination string 74 | firstName = new char [strlen(s.firstName) + 1]; 75 | // then copy source to destination string 76 | strcpy(firstName, s.firstName); 77 | lastName = new char [strlen(s.lastName) + 1]; 78 | // data members which are not pointers do not need their 79 | // space allocated for deep copy, such as is done above 80 | strcpy(lastName, s.lastName); 81 | middleInitial = s.middleInitial; 82 | gpa = s.gpa; 83 | // allocate destination string space, then copy contents 84 | currentCourse = new char [strlen(s.currentCourse) + 1]; 85 | strcpy(currentCourse, s.currentCourse); 86 | } 87 | 88 | // Member function definition 89 | Student::~Student() 90 | { 91 | delete firstName; 92 | delete lastName; 93 | delete currentCourse; 94 | } 95 | 96 | // Member function definition 97 | void Student::Print() 98 | { 99 | cout << firstName << " " << middleInitial << ". "; 100 | cout << lastName << " has a gpa of: " << gpa; 101 | cout << " and is enrolled in: " << currentCourse << endl; 102 | } 103 | 104 | 105 | int main() 106 | { 107 | Student s1("Jo", "Muritz", 'Z', 4.0, "C++"); 108 | 109 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 110 | cout << " Enrolled in: " << s1.GetCurrentCourse() << endl; 111 | 112 | s1.SetCurrentCourse("Advanced C++ Programming"); 113 | 114 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 115 | cout << " New course: " << s1.GetCurrentCourse() << endl; 116 | 117 | return 0; 118 | } 119 | 120 | -------------------------------------------------------------------------------- /Chapter05/original/Chp5-Ex9.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To understand const data members and 3 | // the member initialization list 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Student 10 | { 11 | private: 12 | // data members 13 | char *firstName; 14 | char *lastName; 15 | char middleInitial; 16 | float gpa; 17 | char *currentCourse; 18 | const int studentId; // constant data member 19 | public: 20 | // member function prototypes 21 | Student(); // default constructor 22 | Student(const char *, const char *, char, float, const char *, int); 23 | Student(const Student &); // copy constructor 24 | ~Student(); // destructor 25 | void Print(); 26 | const char *GetFirstName() { return firstName; } 27 | const char *GetLastName() { return lastName; } 28 | char GetMiddleInitial() { return middleInitial; } 29 | float GetGpa() { return gpa; } 30 | const char *GetCurrentCourse() { return currentCourse; } 31 | void SetCurrentCourse(const char *); // prototype only 32 | }; 33 | 34 | inline void Student::SetCurrentCourse(const char *c) 35 | { 36 | delete currentCourse; 37 | currentCourse = new char [strlen(c) + 1]; 38 | strcpy(currentCourse, c); 39 | } 40 | 41 | 42 | // Member init. list is used to set studentId and gpa 43 | Student::Student() : studentId(0), gpa(0.0) 44 | { 45 | firstName = lastName = 0; // NULL pointer 46 | middleInitial = '\0'; 47 | currentCourse = 0; 48 | } 49 | 50 | // member init. list is used to set studentId, gpa, and middleInitial 51 | Student::Student(const char *fn, const char *ln, char mi, float avg, 52 | const char *course, int id) : studentId (id), gpa (avg), 53 | middleInitial(mi) 54 | { 55 | firstName = new char [strlen(fn) + 1]; 56 | strcpy(firstName, fn); 57 | lastName = new char [strlen(ln) + 1]; 58 | strcpy(lastName, ln); 59 | currentCourse = new char [strlen(course) + 1]; 60 | strcpy(currentCourse, course); 61 | } 62 | 63 | // member init. list used to set studentId 64 | Student::Student(const Student &s) : studentId (s.studentId) 65 | { 66 | firstName = new char [strlen(s.firstName) + 1]; 67 | strcpy(firstName, s.firstName); 68 | lastName = new char [strlen(s.lastName) + 1]; 69 | strcpy(lastName, s.lastName); 70 | middleInitial = s.middleInitial; 71 | gpa = s.gpa; 72 | currentCourse = new char [strlen(s.currentCourse) + 1]; 73 | strcpy(currentCourse, s.currentCourse); 74 | } 75 | 76 | Student::~Student() 77 | { 78 | delete firstName; 79 | delete lastName; 80 | delete currentCourse; 81 | } 82 | 83 | void Student::Print() 84 | { 85 | cout << firstName << " " << middleInitial << ". "; 86 | cout << lastName << " has a gpa of: " << gpa; 87 | cout << " and is enrolled in: " << currentCourse << endl; 88 | } 89 | 90 | int main() 91 | { 92 | Student s1("Renee", "Alexander", 'Z', 3.7, "C++", 1290); 93 | cout << s1.GetFirstName() << " " << s1.GetLastName(); 94 | cout << " has gpa of: " << s1.GetGpa() << endl; 95 | 96 | return 0; 97 | } 98 | -------------------------------------------------------------------------------- /Chapter05/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter06/Assessments/ReadMeChp6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter06/Assessments/ReadMeChp6.pdf -------------------------------------------------------------------------------- /Chapter06/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 6. 2 | -------------------------------------------------------------------------------- /Chapter06/original/Chp6-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a simple encapsulated LinkList. 3 | 4 | #include 5 | using namespace std; 6 | 7 | typedef int Item; 8 | 9 | class LinkListElement 10 | { 11 | private: 12 | void *data; 13 | LinkListElement *next; 14 | public: 15 | LinkListElement() { data = 0; next = 0; } 16 | LinkListElement(Item *i) { data = i; next = 0; } 17 | ~LinkListElement() { delete (Item *) data; next = 0; } 18 | void *GetData() { return data; } 19 | LinkListElement *GetNext() { return next; } 20 | void SetNext(LinkListElement *e) { next = e; } 21 | }; 22 | 23 | class LinkList 24 | { 25 | private: 26 | LinkListElement *head; 27 | LinkListElement *tail; 28 | LinkListElement *current; 29 | public: 30 | LinkList(); 31 | LinkList(LinkListElement *); 32 | ~LinkList(); 33 | void InsertAtFront(Item *); 34 | LinkListElement *RemoveAtFront(); 35 | void DeleteAtFront(); 36 | int IsEmpty() { return head == 0; } 37 | void Print(); 38 | }; 39 | 40 | LinkList::LinkList() 41 | { 42 | head = tail = current = 0; 43 | } 44 | 45 | LinkList::LinkList(LinkListElement *element) 46 | { 47 | head = tail = current = element; 48 | } 49 | 50 | void LinkList::InsertAtFront(Item *theItem) 51 | { 52 | LinkListElement *temp = new LinkListElement(theItem); 53 | 54 | temp->SetNext(head); // temp->next = head; 55 | head = temp; 56 | } 57 | 58 | LinkListElement *LinkList::RemoveAtFront() 59 | { 60 | LinkListElement *remove = head; 61 | head = head->GetNext(); // head = head->next; 62 | current = head; // reset current for usage elsewhere 63 | return remove; 64 | } 65 | 66 | void LinkList::DeleteAtFront() 67 | { 68 | LinkListElement *deallocate; 69 | deallocate = RemoveAtFront(); 70 | delete deallocate; // destructor will delete data, set next to NULL 71 | } 72 | 73 | void LinkList::Print() 74 | { 75 | Item output; 76 | 77 | if (!head) 78 | cout << ""; 79 | current = head; 80 | while (current) 81 | { 82 | output = *((Item *) current->GetData()); 83 | cout << output << " "; 84 | current = current->GetNext(); 85 | } 86 | cout << endl; 87 | } 88 | 89 | LinkList::~LinkList() 90 | { 91 | while (!IsEmpty()) 92 | DeleteAtFront(); 93 | } 94 | 95 | int main() 96 | { 97 | // Create a few items, which will later be data for LinkListElements 98 | Item *item1 = new Item; 99 | *item1 = 100; 100 | Item *item2 = new Item(200); 101 | 102 | // create an element for the Linked List 103 | LinkListElement *element1 = new LinkListElement(item1); 104 | 105 | // create a linked list and initialize with one node (element) 106 | LinkList list1(element1); 107 | 108 | // Add some new items to the list 109 | list1.InsertAtFront(item2); 110 | list1.InsertAtFront(new Item(50)); // add a nameless item to the list 111 | 112 | cout << "List 1: "; 113 | list1.Print(); // print out contents of list 114 | 115 | // delete elements from list, one by one 116 | while (!(list1.IsEmpty())) 117 | { 118 | list1.DeleteAtFront(); 119 | cout << "List 1 after removing an item: "; 120 | list1.Print(); 121 | } 122 | 123 | // create a second linked list, add some items and print 124 | LinkList list2; 125 | list2.InsertAtFront(new Item (3000)); 126 | list2.InsertAtFront(new Item (600)); 127 | list2.InsertAtFront(new Item (475)); 128 | 129 | cout << "List 2: "; 130 | list2.Print(); 131 | 132 | // delete elements from list, one by one 133 | while (!(list2.IsEmpty())) 134 | { 135 | list2.DeleteAtFront(); 136 | cout << "List 2 after removing an item: "; 137 | list2.Print(); 138 | } 139 | 140 | return 0; 141 | } 142 | -------------------------------------------------------------------------------- /Chapter06/original/Chp6-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate private inheritance versus public inheritance 3 | 4 | #include 5 | using namespace std; 6 | 7 | typedef int Item; 8 | 9 | class LinkListElement 10 | { 11 | private: 12 | void *data; 13 | LinkListElement *next; 14 | public: 15 | LinkListElement() { data = 0; next = 0; } 16 | LinkListElement(Item *i) { data = i; next = 0; } 17 | ~LinkListElement() { delete (Item *) data; next = 0; } 18 | void *GetData() { return data; } 19 | LinkListElement *GetNext() { return next; } 20 | void SetNext(LinkListElement *e) { next = e; } 21 | }; 22 | 23 | class LinkList 24 | { 25 | private: 26 | LinkListElement *head; 27 | LinkListElement *tail; 28 | LinkListElement *current; 29 | public: 30 | LinkList(); 31 | LinkList(LinkListElement *); 32 | ~LinkList(); 33 | void InsertAtFront(Item *); 34 | LinkListElement *RemoveAtFront(); 35 | void DeleteAtFront(); 36 | int IsEmpty() { return head == 0; } 37 | void Print(); 38 | }; 39 | 40 | LinkList::LinkList() 41 | { 42 | head = tail = current = 0; 43 | } 44 | 45 | LinkList::LinkList(LinkListElement *element) 46 | { 47 | head = tail = current = element; 48 | } 49 | 50 | void LinkList::InsertAtFront(Item *theItem) 51 | { 52 | LinkListElement *temp = new LinkListElement(theItem); 53 | 54 | temp->SetNext(head); // temp->next = head; 55 | head = temp; 56 | } 57 | 58 | LinkListElement *LinkList::RemoveAtFront() 59 | { 60 | LinkListElement *remove = head; 61 | head = head->GetNext(); // head = head->next; 62 | current = head; // reset current for usage elsewhere 63 | return remove; 64 | } 65 | 66 | void LinkList::DeleteAtFront() 67 | { 68 | LinkListElement *deallocate; 69 | deallocate = RemoveAtFront(); 70 | delete deallocate; // destructor will delete data, set next to NULL 71 | } 72 | 73 | void LinkList::Print() 74 | { 75 | Item output; 76 | 77 | if (!head) 78 | cout << ""; 79 | current = head; 80 | while (current) 81 | { 82 | output = *((Item *) current->GetData()); 83 | cout << output << " "; 84 | current = current->GetNext(); 85 | } 86 | cout << endl; 87 | } 88 | 89 | LinkList::~LinkList() 90 | { 91 | while (!IsEmpty()) 92 | DeleteAtFront(); 93 | } 94 | 95 | class Stack : private LinkList 96 | { 97 | private: 98 | // no new data members are necessary 99 | public: 100 | Stack() : LinkList() { } 101 | ~Stack() { } 102 | // Here, we specify the pubilc interface which Stack instances may utilize. 103 | // With private inheritance, the protected and public members inherited 104 | // from LinkList act as though they were defined by Stack as private 105 | // (i.e. and are now ONLY accessible through the scope of Stack). 106 | void Push(Item *i) { InsertAtFront(i); } 107 | Item *Pop(); 108 | // It is necessary to redefine these operations--LinkList is a private base class 109 | int IsEmpty() { return LinkList::IsEmpty(); } 110 | void Print() { LinkList::Print(); } 111 | }; 112 | 113 | Item *Stack::Pop() 114 | { 115 | LinkListElement *temp; 116 | temp = RemoveAtFront(); 117 | Item *item = new Item(*((Item *) temp->GetData())); // copy temp's data 118 | delete temp; 119 | return item; 120 | } 121 | 122 | int main() 123 | { 124 | Stack stack1; // create a stack 125 | 126 | // Add some items to the stack. Notice that we may only utilize the public 127 | // interface provided by Stack to add items--to instances of stack, the public 128 | // interface of LinkList acts as though it is private to Stack, and hence not 129 | // accessible from the scope of main. 130 | stack1.Push(new Item (3000)); 131 | stack1.Push(new Item (600)); 132 | stack1.Push(new Item (475)); 133 | 134 | cout << "Stack 1: "; 135 | stack1.Print(); 136 | 137 | // pop elements from stack, one by one 138 | while (!(stack1.IsEmpty())) 139 | { 140 | stack1.Pop(); 141 | cout << "Stack 1 after popping an item: "; 142 | stack1.Print(); 143 | } 144 | 145 | return 0; 146 | } 147 | -------------------------------------------------------------------------------- /Chapter06/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter07/Assessments/ReadMeChp7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter07/Assessments/ReadMeChp7.pdf -------------------------------------------------------------------------------- /Chapter07/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 7. 2 | -------------------------------------------------------------------------------- /Chapter07/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter08/Assessments/Chp8-Q1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved 2 | // Sample Solution Chp 8, Question 1, parts a - d 3 | // Note: we could have also chosen to store area in Shape. Here, we calculate it with CalcArea() each time. 4 | 5 | #include 6 | #include 7 | using std::cout; // preferred to: using namespace std; 8 | using std::endl; 9 | using std::setprecision; 10 | using std::string; 11 | 12 | constexpr float PI = (float) 3.14159; 13 | constexpr int MAX = 5; 14 | 15 | class Shape 16 | { 17 | private: 18 | string name; 19 | public: 20 | // Notice that we are eliminating the default constructor interface 21 | Shape(string n) : name(n) { cout << "Shape constructor" << endl; } 22 | const string &GetName() { return name; } 23 | virtual ~Shape() { cout << "Shape destructor" << endl; } 24 | virtual float CalcArea() = 0; 25 | }; 26 | 27 | class Circle: public Shape 28 | { 29 | private: 30 | float radius = 0.0; 31 | public: 32 | // Notice that we are eliminating the default constructor interface 33 | Circle(float rad) : Shape("Circle"), radius(rad) { cout << "Circle constructor" << endl; } 34 | ~Circle() override { cout << "Circle destructor" << endl; } 35 | float CalcArea() override; 36 | }; 37 | 38 | float Circle::CalcArea() 39 | { 40 | return (PI * radius * radius); 41 | } 42 | 43 | class Triangle: public Shape 44 | { 45 | private: 46 | float base = 0.0; 47 | float height = 0.0; 48 | public: 49 | // Notice that we are eliminating the default constructor interface 50 | Triangle(float, float); 51 | ~Triangle() override { cout << "Triangle destructor" << endl; } 52 | float CalcArea() override; 53 | }; 54 | 55 | Triangle::Triangle(float b, float ht): Shape("Triangle"), base(b), height(ht) 56 | { 57 | cout << "Triangle constructor" << endl; 58 | } 59 | 60 | 61 | float Triangle::CalcArea() 62 | { 63 | return (.5 * base * height); 64 | } 65 | 66 | class Square: public Shape 67 | { 68 | private: 69 | float side = 0.0; 70 | public: 71 | // Notice that we are eliminating the default constructor interface 72 | Square(float); 73 | ~Square() override { cout << "Square destructor" << endl; } 74 | float CalcArea() override; 75 | }; 76 | 77 | Square::Square(float len): Shape("Square"), side(len) 78 | { 79 | cout << "Square constructor" << endl; 80 | } 81 | 82 | 83 | float Square::CalcArea() 84 | { 85 | return (side * side); 86 | } 87 | 88 | int main() 89 | { 90 | Shape *shapes[MAX] = { }; // initialize to nullptrs 91 | 92 | shapes[0] = new Circle(2.2); 93 | shapes[1] = new Square(4.2); 94 | shapes[2] = new Triangle(1.2, 2.3); 95 | shapes[3] = new Triangle(2.0, 3.0); 96 | shapes[4] = new Circle(5.0); 97 | 98 | cout.setf(std::ios::showpoint); // show decimal points even for values with .00 after decimal point 99 | 100 | // Instead of the following looping style, we can instead use the style below this grouping. 101 | // for (int i = 0; i < MAX; i++) 102 | // { 103 | // cout << "The " << shapes[i]->GetName(); 104 | // cout << " has an area of " << setprecision(3) << shapes[i]->CalcArea() << endl; 105 | // } 106 | 107 | // Here is a more modern style loop to process the shape: 108 | for (auto *iter : shapes) 109 | { 110 | cout << "The " << iter->GetName(); 111 | cout << " has an area of " << setprecision(3) << iter->CalcArea() << endl; 112 | } 113 | 114 | // Instead of the following looping style to deallocate memory: 115 | // for (int i = 0; i < MAX; i++) 116 | // delete shapes[i]; 117 | 118 | // We can use a more modern style: 119 | for (auto iter : shapes) 120 | delete iter; 121 | 122 | return 0; 123 | } 124 | -------------------------------------------------------------------------------- /Chapter08/Assessments/ReadMeChp8.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter08/Assessments/ReadMeChp8.pdf -------------------------------------------------------------------------------- /Chapter08/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 8. 2 | -------------------------------------------------------------------------------- /Chapter08/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter09/Assessments/ReadMeChp9.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter09/Assessments/ReadMeChp9.pdf -------------------------------------------------------------------------------- /Chapter09/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 9. 2 | -------------------------------------------------------------------------------- /Chapter09/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter10/Assessments/ReadMeChp10.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter10/Assessments/ReadMeChp10.pdf -------------------------------------------------------------------------------- /Chapter10/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 10. 2 | -------------------------------------------------------------------------------- /Chapter10/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter11/Assessments/ReadMeChp11.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter11/Assessments/ReadMeChp11.pdf -------------------------------------------------------------------------------- /Chapter11/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 11. 2 | -------------------------------------------------------------------------------- /Chapter11/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter12/Assessments/ReadMeChp12.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter12/Assessments/ReadMeChp12.pdf -------------------------------------------------------------------------------- /Chapter12/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 12. 2 | -------------------------------------------------------------------------------- /Chapter12/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter13/Assessments/ReadMeChp13.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter13/Assessments/ReadMeChp13.pdf -------------------------------------------------------------------------------- /Chapter13/Chp13-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To demonstrate a simple template function. 3 | 4 | #include 5 | #include 6 | 7 | using std::cout; // preferred to: using namespace std; 8 | using std::endl; 9 | 10 | // template function prototype 11 | template Type2 ChooseFirst(Type1, Type2); 12 | 13 | 14 | template // template preamble 15 | Type2 ChooseFirst(Type1 x, Type2 y) // template function 16 | { 17 | if (x < y) 18 | return static_cast(x); // Note: cast here is optional - it will happen automatically with return statement 19 | else 20 | return y; 21 | } 22 | 23 | int main() 24 | { 25 | int value1 = 4, value2 = 7; 26 | float value3 = 5.67f; 27 | cout << "First: " << ChooseFirst(value1, value3) << endl; 28 | cout << "First: " << ChooseFirst(value2, value1) << endl; 29 | } 30 | -------------------------------------------------------------------------------- /Chapter13/Chp13-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To demonstrate a simple template class -- an Array of any data type. 3 | // This baseline class employs bounds checking and can easily be augmented to allow resizing. 4 | 5 | #include 6 | #include 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::to_string; 11 | using std::out_of_range; 12 | 13 | template // template class preamble 14 | class Array 15 | { 16 | private: 17 | int numElements = 0; // in-class init; will be over written after successful completion of alt constructor 18 | Type *contents = nullptr; 19 | public: 20 | Array(int size) : numElements(size), contents(new Type [size]) 21 | { // note: allocation done in the member initialization list above 22 | } 23 | ~Array() { delete [] contents; } 24 | void Print() const 25 | { 26 | for (int i = 0; i < numElements; i++) 27 | cout << contents[i] << " "; 28 | cout << endl; 29 | } 30 | Type &operator[](int index) 31 | { 32 | if (index < numElements) 33 | return contents[index]; 34 | else 35 | throw::std::out_of_range(std::to_string(index)); 36 | } 37 | void operator+(Type); 38 | }; 39 | 40 | template 41 | void Array::operator+(Type item) 42 | { 43 | // resize array if necessary, add new data element and increment numElements 44 | } 45 | 46 | int main() 47 | { 48 | Array a1(3); // create an ArrayInt of 3 elements 49 | try 50 | { 51 | a1[2] = 12; 52 | a1[1] = 70; 53 | a1[0] = 2; 54 | a1[100] = 10; // this assignments throws an exception, caught below 55 | } 56 | catch (const std::out_of_range &e) 57 | { 58 | cout << "Out of range: index " << e.what() << endl; 59 | } 60 | a1.Print(); 61 | } 62 | 63 | -------------------------------------------------------------------------------- /Chapter13/Chp13-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a more complete example with template functions and classes. 3 | // This example modifies our previous void * LinkList/LinkListElement pair to use templates. 4 | 5 | #include 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | template class LinkList; // forward declaration 10 | // with template preamble 11 | template // template preamble for class def 12 | class LinkListElement 13 | { 14 | private: 15 | Type *data = nullptr; // in-class initialization 16 | LinkListElement *next = nullptr; 17 | // private access methods to be used in scope of friend 18 | Type *GetData() const { return data; } 19 | LinkListElement *GetNext() const { return next; } 20 | void SetNext(LinkListElement *e) { next = e; } 21 | public: 22 | friend class LinkList; 23 | LinkListElement() = default; 24 | LinkListElement(Type *i) : data(i), next(nullptr) { } 25 | ~LinkListElement(){ delete data; next = nullptr;} 26 | }; 27 | 28 | // LinkList should only be extended as a protected or private base class; it does not contain a virtual destructor. 29 | // It can be used as-is, or as implementation for another ADT. 30 | 31 | template 32 | class LinkList 33 | { 34 | private: 35 | LinkListElement *head = nullptr, *tail = nullptr, *current = nullptr; // in-class initialization 36 | public: 37 | LinkList() = default; 38 | LinkList(LinkListElement *e) { head = tail = current = e; } 39 | void InsertAtFront(Type *); 40 | LinkListElement *RemoveAtFront(); 41 | void DeleteAtFront() { delete RemoveAtFront(); } 42 | bool IsEmpty() const { return head == nullptr; } 43 | void Print() const; 44 | ~LinkList() { while (!IsEmpty()) DeleteAtFront(); } 45 | }; 46 | 47 | // If we chose to write the default constructor (versus in-class initialization), it might look like this (or use mbr init list) 48 | /* 49 | LinkList::LinkList() 50 | { 51 | head = tail = current = nullptr; 52 | } 53 | */ 54 | 55 | template 56 | void LinkList::InsertAtFront(Type *theItem) 57 | { 58 | LinkListElement *newHead; 59 | newHead = new LinkListElement(theItem); 60 | newHead->SetNext(head); // newHead->next = head; 61 | head = newHead; 62 | } 63 | 64 | template 65 | LinkListElement *LinkList::RemoveAtFront() 66 | { 67 | LinkListElement *remove = head; 68 | head = head->GetNext(); // head = head->next; 69 | current = head; // reset current for usage elsewhere 70 | return remove; 71 | } 72 | 73 | template 74 | void LinkList::Print() const 75 | { 76 | if (!head) 77 | cout << "" << endl; 78 | LinkListElement *traverse = head; 79 | while (traverse) 80 | { 81 | Type output = *(traverse->GetData()); 82 | cout << output << ' '; 83 | traverse = traverse->GetNext(); 84 | } 85 | cout << endl; 86 | } 87 | 88 | int main() 89 | { 90 | LinkList list1; // create a LinkList of ints 91 | list1.InsertAtFront(new int (3000)); 92 | list1.InsertAtFront(new int (600)); 93 | list1.InsertAtFront(new int (475)); 94 | cout << "List 1: "; 95 | list1.Print(); 96 | // delete elements from list, one by one 97 | while (!(list1.IsEmpty())) 98 | { 99 | list1.DeleteAtFront(); 100 | cout << "List 1 after removing an item: "; 101 | list1.Print(); 102 | } 103 | 104 | LinkList list2; // now make a LinkList of floats 105 | list2.InsertAtFront(new float(30.50)); 106 | list2.InsertAtFront(new float (60.89)); 107 | list2.InsertAtFront(new float (45.93)); 108 | cout << "List 2: "; 109 | list2.Print(); 110 | 111 | return 0; 112 | } 113 | 114 | -------------------------------------------------------------------------------- /Chapter13/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 13. 2 | -------------------------------------------------------------------------------- /Chapter13/original/Chp13-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To demonstrate a simple template function. 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | // template function prototype 11 | template Type2 ChooseFirst(Type1, Type2); 12 | 13 | 14 | template // template preamble 15 | Type2 ChooseFirst(Type1 x, Type2 y) // template function 16 | { 17 | if (x < y) 18 | return x; 19 | else 20 | return y; 21 | } 22 | 23 | int main() 24 | { 25 | int value1 = 4, value2 = 7; 26 | float value3 = 5.67f; 27 | cout << "First: " << ChooseFirst(value1, value3) << endl; 28 | cout << "First: " << ChooseFirst(value2, value1) << endl; 29 | } 30 | -------------------------------------------------------------------------------- /Chapter13/original/Chp13-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To demonstrate a simple template class -- an Array of any data type. 3 | // This baseline class employs bounds checking and can easily be augmented to allow resizing. 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | template // template class preamble 12 | class Array 13 | { 14 | private: 15 | int numElements; 16 | Type *contents; 17 | public: 18 | Array(int size) : numElements(size) { contents = new Type [size]; } 19 | ~Array() { delete contents; } 20 | void Print() const 21 | { 22 | for (int i = 0; i < numElements; i++) 23 | cout << contents[i] << " "; 24 | cout << endl; 25 | } 26 | Type &operator[](int index) 27 | { 28 | if (index < numElements) return contents[index]; 29 | else cout << "Out of bounds" << endl; 30 | } 31 | void operator+(Type); 32 | }; 33 | 34 | template 35 | void Array::operator+(Type item) 36 | { 37 | // resize array if necessary, add new data element and increment numElements 38 | } 39 | 40 | int main() 41 | { 42 | Array a1(3); // create an ArrayInt of 3 elements 43 | a1[2] = 12; 44 | a1[1] = 70; 45 | a1[0] = 2; 46 | a1.Print(); 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Chapter13/original/Chp13-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a more complete example with template functions and classes. 3 | // This example modifies our previous void * LinkList/LinkListElement pair to use templates. 4 | 5 | #include 6 | using namespace std; 7 | 8 | template class LinkList; // forward declaration 9 | // with template preamble 10 | template // template preamble for class def 11 | class LinkListElement 12 | { 13 | private: 14 | Type *data; 15 | LinkListElement *next; 16 | // private access methods to be used in scope of friend 17 | Type *GetData() { return data; } 18 | LinkListElement *GetNext() { return next; } 19 | void SetNext(LinkListElement *e) { next = e; } 20 | public: 21 | friend class LinkList; 22 | LinkListElement() { data = 0; next = 0; } 23 | LinkListElement(Type *i) { data = i; next = 0; } 24 | ~LinkListElement(){ delete data; next = 0;} 25 | }; 26 | 27 | template 28 | class LinkList 29 | { 30 | private: 31 | LinkListElement *head, *tail, *current; 32 | public: 33 | LinkList() { head = tail = current = 0; } 34 | LinkList(LinkListElement *e) 35 | { head = tail = current = e; } 36 | void InsertAtFront(Type *); 37 | LinkListElement *RemoveAtFront(); 38 | void DeleteAtFront() { delete RemoveAtFront(); } 39 | int IsEmpty() { return head == 0; } 40 | void Print(); 41 | ~LinkList() { while (!IsEmpty()) DeleteAtFront(); } 42 | }; 43 | 44 | template 45 | void LinkList::InsertAtFront(Type *theItem) 46 | { 47 | LinkListElement *temp; 48 | temp = new LinkListElement(theItem); 49 | temp->SetNext(head); // temp->next = head; 50 | head = temp; 51 | } 52 | 53 | template 54 | LinkListElement *LinkList::RemoveAtFront() 55 | { 56 | LinkListElement *remove = head; 57 | head = head->GetNext(); // head = head->next; 58 | current = head; // reset current for usage elsewhere 59 | return remove; 60 | } 61 | 62 | template 63 | void LinkList::Print() 64 | { 65 | Type output; 66 | 67 | if (!head) 68 | cout << "" << endl; 69 | current = head; 70 | while (current) 71 | { 72 | output = *(current->GetData()); 73 | cout << output << " "; 74 | current = current->GetNext(); 75 | } 76 | cout << endl; 77 | } 78 | 79 | int main() 80 | { 81 | LinkList list1; // create a LinkList of ints 82 | list1.InsertAtFront(new int (3000)); 83 | list1.InsertAtFront(new int (600)); 84 | list1.InsertAtFront(new int (475)); 85 | cout << "List 1: "; 86 | list1.Print(); 87 | // delete elements from list, one by one 88 | while (!(list1.IsEmpty())) 89 | { 90 | list1.DeleteAtFront(); 91 | cout << "List 1 after removing an item: "; 92 | list1.Print(); 93 | } 94 | 95 | LinkList list2; // now make a LinkList of floats 96 | list2.InsertAtFront(new float(30.50)); 97 | list2.InsertAtFront(new float (60.89)); 98 | list2.InsertAtFront(new float (45.93)); 99 | cout << "List 2: "; 100 | list2.Print(); 101 | 102 | return 0; 103 | } 104 | 105 | -------------------------------------------------------------------------------- /Chapter13/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter14/Assessments/ReadMeChp14.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter14/Assessments/ReadMeChp14.pdf -------------------------------------------------------------------------------- /Chapter14/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 14. 2 | -------------------------------------------------------------------------------- /Chapter14/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter15/Assessments/ReadMeChp15.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter15/Assessments/ReadMeChp15.pdf -------------------------------------------------------------------------------- /Chapter15/Chp15-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate items to include in a driver to test a class. 3 | // Sample driver to test the Student class. 4 | 5 | #include 6 | #include 7 | #include 8 | #include "Person.h" 9 | #include "Student.h" 10 | 11 | using std::cout; 12 | using std::endl; 13 | 14 | constexpr int MAX = 3; 15 | 16 | int main() 17 | { 18 | // Test all means for instantiation, including copy constructor 19 | Student s0; // Default construction 20 | 21 | // instantiate two Students 22 | Student s1("Jo", "Li", 'H', "Ms.", 3.7, "C++", "UD1234"); 23 | Student s2("Sam", "Lo", 'A', "Mr.", 3.5, "C++", "UD2245"); 24 | 25 | // These initializations implicitly invoke copy constructor 26 | Student s3(s1); 27 | Student s4 = s2; 28 | 29 | // Test the assignment operator 30 | Student s5("Ren", "Ze", 'A', "Dr.", 3.8, "C++", "BU5563"); 31 | Student s6; 32 | s6 = s5; // this is an assignment, not initialization 33 | 34 | // Test each public method. A sample is shown here. Be sure to test ALL methods. 35 | s1.Print(); 36 | s3.Print(); 37 | s2.Print(); 38 | s4.Print(); 39 | 40 | // Generalize derived instances as base types -- do methods work as expected? 41 | Person *people[MAX] { }; // will be initialized to nullptrs 42 | people[0] = new Person("Juliet", "Martinez", 'M', "Ms."); // base instance for comparison 43 | people[1] = new Student("Zack", "Moon", 'R', "Dr.", 3.8, "C++", "UMD1234"); // derived instances 44 | people[2] = new Student("Gabby", "Doone", 'A', "Dr.", 3.9, "C++", "GWU4321"); 45 | 46 | // Compare range for loop to older style, further below 47 | for (auto *item : people) // note item is a Person (auto can determine this); can also use: for (auto item : people) 48 | { 49 | item->IsA(); 50 | cout << " "; 51 | item->Print(); 52 | } 53 | 54 | // Less-modern looping style 55 | /* 56 | for (int i = 0; i < MAX; i++) 57 | { 58 | people[i]->IsA(); 59 | cout << " "; 60 | people[i]->Print(); 61 | } 62 | */ 63 | 64 | // Test destruction sequence (for dynamically allocated instances) 65 | // Compare range for loop to older style below 66 | for (auto *item : people) // can also use: for (auto item : people) 67 | delete item; // engage virtual dest. sequence 68 | 69 | // Older style looping for comparison with preferred loop style, just above 70 | // for (int i = 0; i < MAX; i++) 71 | // delete people[i]; // engage virtual dest. sequence 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /Chapter15/Person.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Person class header file 3 | 4 | #ifndef _PERSON_H 5 | #define _PERSON_H 6 | 7 | using std::string; 8 | 9 | class Person 10 | { 11 | private: 12 | string firstName; 13 | string lastName; 14 | char middleInitial = '\0'; // in-class initialization 15 | char *title = nullptr; // we'll keep this data member as a char * to demonstrate deep copy/assignment 16 | protected: 17 | void ModifyTitle(const string &); 18 | public: 19 | Person() = default; // default constructor 20 | Person(const string &, const string &, char, const char *); 21 | Person(const Person &); // copy constructor 22 | Person(Person &&); // move copy constructor 23 | virtual ~Person(); // virtual destructor 24 | 25 | // inline function definitions 26 | const string &GetFirstName() const { return firstName; } 27 | const string &GetLastName() const { return lastName; } 28 | const char *GetTitle() const { return title; } 29 | char GetMiddleInitial() const { return middleInitial; } 30 | 31 | const string &SetLastName(const string &); 32 | 33 | // Virtual functions will (usually) not be inlined since their method must be determined at run time using v-table (except rare cases) 34 | virtual void Print() const; 35 | virtual void IsA() const; 36 | virtual void Greeting(const string &) const; 37 | 38 | Person &operator=(const Person &); // overloaded assignment operator prototype 39 | Person &operator=(Person &&); // move overloaded assignment operator prototype 40 | 41 | }; 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /Chapter15/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 15. 2 | -------------------------------------------------------------------------------- /Chapter15/Student.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate Student.h header file 3 | 4 | #ifndef _STUDENT_H 5 | #define _STUDENT_H 6 | 7 | #include "Person.h" 8 | 9 | class Student : public Person 10 | { 11 | private: 12 | // data members 13 | float gpa = 0.0; // in-class initialization 14 | string currentCourse; 15 | const char *studentId; // Again, we have one pointer data member to demonstrate deep copy / assignment 16 | static int numStudents; 17 | public: 18 | // member function prototypes 19 | Student(); // default constructor 20 | Student(const string &, const string &, char, const char *, 21 | float, const string &, const char *); 22 | Student(const Student &); // copy constructor 23 | Student(Student &&); // move copy constructor 24 | ~Student() override; // virtual destructor 25 | void EarnPhD(); 26 | // inline function definitions 27 | float GetGpa() const { return gpa; } 28 | const string &GetCurrentCourse() const { return currentCourse; } 29 | const char *GetStudentId() const { return studentId; } 30 | void SetCurrentCourse(const string &); // prototype only 31 | 32 | // In the derived class, the keyword virtual is optional for overridden (polymorphic) methods, as is the keyword "override" 33 | // Currently, "override" is recommended for internal documentation, however "virtual" is not recommended 34 | void Print() const override; 35 | void IsA() const override; 36 | // note: we choose not to redefine Person::Greeting(const Student &) const 37 | Student &operator=(const Student &); // overloaded assignment operator prototype 38 | Student &operator=(Student &&); // overloaded move assignment operator prototype 39 | 40 | static int GetNumberStudents(); 41 | }; 42 | 43 | inline void Student::SetCurrentCourse(const string &c) 44 | { 45 | currentCourse = c; 46 | } 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /Chapter15/original/Chp15-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate items to include in a driver to test a class. 3 | // Sample driver to test the Student class. 4 | 5 | #include 6 | #include 7 | #include 8 | #include "Person.h" 9 | #include "Student.h" 10 | 11 | using namespace std; 12 | 13 | const int MAX = 3; 14 | 15 | int main() 16 | { 17 | // Test all means for instantiation, including copy constructor 18 | Student s0; // Default construction 19 | 20 | // instantiate two Students 21 | Student s1("Jo", "Li", 'H', "Ms.", 3.7, "C++", "UD1234"); 22 | Student s2("Sam", "Lo", 'A', "Mr.", 3.5, "C++", "UD2245"); 23 | 24 | // These initializations implicitly invoke copy constructor 25 | Student s3(s1); 26 | Student s4 = s2; 27 | 28 | // Test the assignment operator 29 | Student s5("Ren", "Ze", 'A', "Dr.", 3.8, "C++", "BU5563"); 30 | Student s6; 31 | s6 = s5; // this is an assignment, not initialization 32 | 33 | // Test each public method. A sample is shown here. Be sure to test ALL methods. 34 | s1.Print(); 35 | s3.Print(); 36 | s2.Print(); 37 | s4.Print(); 38 | 39 | // Generalize derived instances as base types -- do methods work as expected? 40 | Person *people[MAX]; 41 | people[0] = new Person("Juliet", "Martinez", 'M', "Ms."); // base instance for comparison 42 | people[1] = new Student("Zack", "Moon", 'R', "Dr.", 3.8, "C++", "UMD1234"); // derived instances 43 | people[2] = new Student("Gabby", "Doone", 'A', "Dr.", 3.9, "C++", "GWU4321"); 44 | 45 | for (int i = 0; i < MAX; i++) 46 | { 47 | people[i]->IsA(); 48 | cout << " "; 49 | people[i]->Print(); 50 | } 51 | 52 | // Test destruction sequence (for dynamically allocated instances) 53 | for (int i = 0; i < MAX; i++) 54 | delete people[i]; // engage virtual dest. sequence 55 | 56 | return 0; 57 | } 58 | 59 | -------------------------------------------------------------------------------- /Chapter15/original/Person.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate Person.cpp source code 3 | 4 | #include 5 | #include 6 | #include 7 | #include "Person.h" 8 | 9 | using namespace std; 10 | 11 | Person::Person() 12 | { 13 | firstName = lastName = 0; // NULL pointer 14 | middleInitial = '\0'; 15 | title = 0; 16 | } 17 | 18 | Person::Person(const char *fn, const char *ln, char mi, 19 | const char *t) 20 | { 21 | firstName = new char [strlen(fn) + 1]; 22 | strcpy(firstName, fn); 23 | lastName = new char [strlen(ln) + 1]; 24 | strcpy(lastName, ln); 25 | middleInitial = mi; 26 | title = new char [strlen(t) + 1]; 27 | strcpy(title, t); 28 | } 29 | 30 | // copy constructor 31 | Person::Person(const Person &pers) 32 | { 33 | firstName = new char [strlen(pers.firstName) + 1]; 34 | strcpy(firstName, pers.firstName); 35 | lastName = new char [strlen(pers.lastName) + 1]; 36 | strcpy(lastName, pers.lastName); 37 | middleInitial = pers.middleInitial; 38 | title = new char [strlen(pers.title) + 1]; 39 | strcpy(title, pers.title); 40 | } 41 | 42 | Person::~Person() 43 | { 44 | delete firstName; 45 | delete lastName; 46 | delete title; 47 | } 48 | 49 | void Person::ModifyTitle(const char *newTitle) 50 | { 51 | delete title; // delete old title 52 | title = new char [strlen(newTitle) + 1]; 53 | strcpy(title, newTitle); 54 | } 55 | 56 | void Person::Print() const 57 | { 58 | if (title) 59 | cout << title << " "; 60 | if (firstName) 61 | cout << firstName << " "; 62 | else 63 | cout << "No first name "; 64 | if (middleInitial != '\0') 65 | cout << middleInitial << ". "; 66 | if (lastName) 67 | cout << lastName << endl; 68 | else 69 | cout << "No last name" << endl; 70 | } 71 | 72 | void Person::IsA() 73 | { 74 | cout << "Person" << endl; 75 | } 76 | 77 | void Person::Greeting(const char *msg) 78 | { 79 | cout << msg << endl; 80 | } 81 | 82 | // overloaded assignment operator 83 | Person &Person::operator=(const Person &p) 84 | { 85 | // make sure we're not assigning an object to itself 86 | if (this != &p) 87 | { 88 | delete firstName; // or call ~Person(); 89 | delete lastName; 90 | delete title; 91 | 92 | firstName = new char [strlen(p.firstName) + 1]; 93 | strcpy(firstName, p.firstName); 94 | lastName = new char [strlen(p.lastName) + 1]; 95 | strcpy(lastName, p.lastName); 96 | middleInitial = p.middleInitial; 97 | title = new char [strlen(p.title) + 1]; 98 | strcpy(title, p.title); 99 | } 100 | return *this; // allow for cascaded assignments 101 | } 102 | 103 | 104 | -------------------------------------------------------------------------------- /Chapter15/original/Person.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Person class header file 3 | 4 | #ifndef _PERSON_H 5 | #define _PERSON_H 6 | 7 | class Person 8 | { 9 | private: 10 | // data members 11 | char *firstName; 12 | char *lastName; 13 | char middleInitial; 14 | char *title; // Mr., Ms., Mrs., Miss, Dr., etc. 15 | protected: 16 | void ModifyTitle(const char *); 17 | public: 18 | Person(); // default constructor 19 | Person(const char *, const char *, char, const char *); 20 | Person(const Person &); // copy constructor 21 | virtual ~Person(); // virtual destructor 22 | 23 | // inline function definitions 24 | const char *GetFirstName() const { return firstName; } 25 | const char *GetLastName() const { return lastName; } 26 | const char *GetTitle() const { return title; } 27 | char GetMiddleInitial() const { return middleInitial; } 28 | 29 | // Virtual functions will not be inlined since their 30 | // method must be determined at run time using v-table. 31 | virtual void Print() const; 32 | virtual void IsA(); 33 | virtual void Greeting(const char *); 34 | 35 | Person &operator=(const Person &); // overloaded assignment operator prototype 36 | 37 | }; 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /Chapter15/original/ReadMe: -------------------------------------------------------------------------------- 1 | This directory represents the original code files for this book. 2 | -------------------------------------------------------------------------------- /Chapter15/original/Student.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate Student.cpp Source code 3 | 4 | #include 5 | #include 6 | #include 7 | #include "Student.h" 8 | 9 | using namespace std; 10 | 11 | Student::Student() : studentId (0) 12 | { 13 | gpa = 0.0; 14 | currentCourse = 0; 15 | } 16 | 17 | // Alternate constructor member function definition 18 | Student::Student(const char *fn, const char *ln, char mi, 19 | const char *t, float avg, const char *course, 20 | const char *id) : Person(fn, ln, mi, t) 21 | { 22 | gpa = avg; 23 | currentCourse = new char [strlen(course) + 1]; 24 | strcpy(currentCourse, course); 25 | char *temp = new char [strlen(id) + 1]; 26 | strcpy (temp, id); 27 | studentId = temp; 28 | } 29 | 30 | // Copy constructor definition 31 | Student::Student(const Student &ps) : Person(ps) 32 | { 33 | gpa = ps.gpa; 34 | currentCourse = new char [strlen(ps.currentCourse) + 1]; 35 | strcpy(currentCourse, ps.currentCourse); 36 | char *temp = new char [strlen(ps.studentId) + 1]; 37 | strcpy (temp, ps.studentId); 38 | studentId = temp; 39 | } 40 | 41 | // destructor definition 42 | Student::~Student() 43 | { 44 | delete currentCourse; 45 | delete (char *) studentId; 46 | } 47 | 48 | void Student::EarnPhD() 49 | { 50 | ModifyTitle("Dr."); 51 | } 52 | 53 | void Student::Print() const 54 | { // need to use access functions as these data members are 55 | // defined in Person as private 56 | cout << GetTitle() << " " << GetFirstName() << " "; 57 | cout << GetMiddleInitial() << ". " << GetLastName(); 58 | cout << " with id: " << studentId << " GPA: "; 59 | cout << setprecision(3) << " " << gpa; 60 | cout << " Course: " << currentCourse << endl; 61 | } 62 | 63 | void Student::IsA() 64 | { 65 | cout << "Student" << endl; 66 | } 67 | 68 | // overloaded assignment operator 69 | Student &Student::operator=(const Student &s) 70 | { 71 | // make sure we're not assigning an object to itself 72 | if (this != &s) 73 | { 74 | Person::operator=(s); // call base class operator= for help 75 | 76 | delete currentCourse; // delete existing data members 77 | delete studentId; 78 | 79 | gpa = s.gpa; // make deep assignment of data members 80 | currentCourse = new char [strlen(s.currentCourse) + 1]; 81 | strcpy(currentCourse, s.currentCourse); 82 | char *temp = new char [strlen(s.studentId) + 1]; 83 | strcpy (temp, s.studentId); 84 | studentId = temp; 85 | } 86 | return *this; // allow for cascaded assignments 87 | } 88 | 89 | -------------------------------------------------------------------------------- /Chapter15/original/Student.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate Student.h header file 3 | 4 | #ifndef _STUDENT_H 5 | #define _STUDENT_H 6 | 7 | #include "Person.h" 8 | 9 | class Student : public Person 10 | { 11 | private: 12 | // data members 13 | float gpa; 14 | char *currentCourse; 15 | const char *studentId; 16 | public: 17 | // member function prototypes 18 | Student(); // default constructor 19 | Student(const char *, const char *, char, const char *, 20 | float, const char *, const char *); 21 | Student(const Student &); // copy constructor 22 | virtual ~Student(); // destructor 23 | void EarnPhD(); 24 | // inline function definitions 25 | float GetGpa() const { return gpa; } 26 | const char *GetCurrentCourse() const { return currentCourse; } 27 | const char *GetStudentId() const { return studentId; } 28 | void SetCurrentCourse(const char *); // prototype only 29 | 30 | // In the derived class, the keyword virtual is optional, 31 | // but recommended for internal documentation 32 | virtual void Print() const override; 33 | virtual void IsA() override; 34 | // note: we choose not to redefine 35 | // Person::Greeting(const char *) 36 | Student &operator=(const Student &); // overloaded assignment operator prototype 37 | }; 38 | 39 | inline void Student::SetCurrentCourse(const char *c) 40 | { 41 | delete currentCourse; // delete existing course 42 | currentCourse = new char [strlen(c) + 1]; 43 | strcpy(currentCourse, c); 44 | } 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /Chapter16/Assessments/ReadMeChp16.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter16/Assessments/ReadMeChp16.pdf -------------------------------------------------------------------------------- /Chapter16/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 16. 2 | -------------------------------------------------------------------------------- /Chapter16/original/ReadMe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Chapter17/Assessments/ReadMeChp17.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter17/Assessments/ReadMeChp17.pdf -------------------------------------------------------------------------------- /Chapter17/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 17. 2 | -------------------------------------------------------------------------------- /Chapter17/original/ReadMe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Chapter18/Assessments/ReadMeChp18.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter18/Assessments/ReadMeChp18.pdf -------------------------------------------------------------------------------- /Chapter18/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 18. 2 | -------------------------------------------------------------------------------- /Chapter18/original/ReadMe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Chapter19/Assesssments/ReadMeChp19.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter19/Assesssments/ReadMeChp19.pdf -------------------------------------------------------------------------------- /Chapter19/Chp19-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a very simple Singleton implementation. In this implementation, destruction of the Singleton 3 | // is not guaranteed. In fact, it won't happen unless the rare (unadvised) case of explicit deletion of the Singleton occurs. 4 | 5 | #include 6 | using std::cout; // preferred to: using namespace std; 7 | using std::endl; 8 | 9 | class Singleton 10 | { 11 | private: 12 | static Singleton *theInstance; // static pointer will not use in-class initialization, see initialization below 13 | Singleton(); // private to prevent multiple instantiation 14 | public: 15 | static Singleton *instance(); 16 | // destructor is not called, unless you do so explicitly by deleting outer object, which is unlikely and atypical 17 | virtual ~Singleton(); // virtual so you can extend the Singleton with a Target class 18 | }; 19 | 20 | // get the memory for the static data member 21 | Singleton *Singleton::theInstance = nullptr; 22 | 23 | Singleton::Singleton() 24 | { 25 | cout << "Constructor" << endl; 26 | // theInstance = nullptr; // not necessary -- set above with static initialization 27 | } 28 | 29 | Singleton::~Singleton() 30 | { 31 | cout << "Destructor" << endl; // note: this message will appear twice if you delete the Singleton. 32 | if (theInstance != nullptr) // Second ~ call is on delete temp; before this check of theInstance != NULL to stop the recursion 33 | { 34 | Singleton *temp = theInstance; 35 | theInstance = nullptr; // removes pointer to actual Singleton and prevents recursion 36 | // temp->theInstance = nullptr; // actually, since theInstance is static, this assignment is duplicative and not necessary 37 | delete temp; // makes for a recursive destructor call if you'd just call 'delete theInstance;' 38 | // which is why we need to use a temp pointer and first null out 'theInstance' to stop the recursion 39 | // delete theInstance; // Note: this call alone (without temp stuff here) would cause recursion 40 | } 41 | } 42 | 43 | // If you extend the Singleton with a Target class, you will want to move instance() to the Target class. 44 | // The Target class will change the signature to match the signature in its private constructors (to pass the arguments along) 45 | Singleton *Singleton::instance() 46 | { 47 | if (theInstance == nullptr) 48 | theInstance = new Singleton(); // allocate Singleton -- will be constructed (once) 49 | return theInstance; 50 | } 51 | 52 | int main() 53 | { 54 | Singleton *s1 = Singleton::instance(); // first call, creates theInstance 55 | Singleton *s2 = Singleton::instance(); // returns existing theInstance 56 | 57 | cout << s1 << " " << s2 << endl; 58 | 59 | // delete s1; // delete s1 will ensure the destructor is called, 60 | // but this is not typical that a Singleton will be deleted explicitly, 61 | // so depending on this is a poor design choice 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /Chapter19/Chp19-Ex1b.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a very simple Singleton implementation using a referenceable object. Note that the referenceable 3 | // object representing the Singleton will be a static local variable in instance(). It will not be a static data member of the 4 | // class (as that would be initialized before main() and as such, impossible to customize its construction. 5 | // The fallback here is that we always have the singleton, we can never get rid of it to replace it with another singleton. 6 | // This may be ok, but may not be. Consider a Singleton President. We have one. That one goes away, then we have a new one. 7 | // Only one at a time in that scenario, but we'd like the flexibility to change which one it is (for that scenario, a pointer works better). 8 | 9 | #include 10 | using std::cout; // preferred to: using namespace std; 11 | using std::endl; 12 | using std::string; 13 | 14 | class Singleton 15 | { 16 | private: 17 | string data; 18 | Singleton(string d); // private to prevent multiple instantiation 19 | public: 20 | static Singleton &instance(string); 21 | // destructor is called for the static local variable in instance() before the application ends 22 | virtual ~Singleton(); // virtual so you can extend the Singleton with a Target class 23 | const string &getData() const { return data; } 24 | }; 25 | 26 | Singleton::Singleton(string d) : data(d) 27 | { 28 | cout << "Constructor" << endl; 29 | } 30 | 31 | Singleton::~Singleton() 32 | { 33 | cout << "Destructor" << endl; 34 | } 35 | 36 | // If you extend the Singleton with a Target class, you will want to move instance() to the Target class. 37 | // The Target class will change the signature to match the signature in its private constructors (to pass the arguments along) 38 | Singleton &Singleton::instance(string d) 39 | { 40 | static Singleton theInstance(d); // create the Singleton with desired constructor. Note: we can never replace the Singleton in this approach! 41 | // Remember, static local variables are only created and initialized exactly once, guaranteeing one Singleton! 42 | return theInstance; 43 | } 44 | 45 | int main() 46 | { 47 | Singleton &s1 = Singleton::instance("Unique data"); // first call, creates theInstance 48 | Singleton &s2 = Singleton::instance("More data"); // returns existing theInstance 49 | 50 | cout << s1.getData() << "\n" << s2.getData() << endl; 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Chapter19/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 19. 2 | -------------------------------------------------------------------------------- /Chapter19/original/Chp19-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate a very simple Singleton implementation. In this implementation, destruction of the Singleton 3 | // is not guaranteed. In fact, it won't happen unless the rare (unadvised) case of explicit deletion of the Singleton occurs. 4 | 5 | #include 6 | using namespace std; 7 | 8 | class Singleton 9 | { 10 | private: 11 | static Singleton *theInstance; 12 | Singleton(); // private to prevent multiple instantiation 13 | public: 14 | static Singleton *instance(); 15 | // destructor is not called, unless you do so explicitly by deleting outer object, which is unlikely and atypical 16 | virtual ~Singleton(); // virtual so you can extend the Singleton with a Target class 17 | }; 18 | 19 | // get the memory for the static data member 20 | Singleton *Singleton::theInstance = NULL; 21 | 22 | Singleton::Singleton() 23 | { 24 | cout << "Constructor" << endl; 25 | theInstance = NULL; 26 | } 27 | 28 | Singleton::~Singleton() 29 | { 30 | cout << "Destructor" << endl; // note: this message will appear twice if you delete the Singleton. 31 | if (theInstance != NULL) // Second call (print) is on delete temp; before this check of theInstance != NULL to stop the recursion 32 | { 33 | Singleton *temp = theInstance; 34 | theInstance = NULL; // removes pointer to actual Singleton 35 | temp->theInstance = NULL; // prevents recursion 36 | delete temp; // makes for a recursive destructor call if you'd just call 'delete theInstance;' 37 | } // which is why we need to use a temp pointer and first null out 'theInstance' to stop the recursion 38 | } 39 | 40 | // If you extend the Singleton with a Target class, you will want to move instance() to the Target class. 41 | // The Target class will change the signature to match the signature in its private constructors (to pass the arguments along) 42 | Singleton *Singleton::instance() 43 | { 44 | if (theInstance == NULL) 45 | theInstance = new Singleton(); // allocate Singleton -- will be constructed (once) 46 | return theInstance; 47 | } 48 | 49 | int main() 50 | { 51 | Singleton *s1 = Singleton::instance(); // first call, creates theInstance 52 | Singleton *s2 = Singleton::instance(); // returns existing theInstance 53 | 54 | cout << s1 << " " << s2 << endl; 55 | 56 | // delete s1; // delete s1 will ensure the destructor is called, 57 | } // but this is not typical that a Singleton will be deleted explicitly, 58 | // so depending on this is a poor design choice 59 | -------------------------------------------------------------------------------- /Chapter19/original/ReadMe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Chapter20/Assessments/ReadMeChp20.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP/076390c924ed36d182f54db48431bb9cdc35c1bf/Chapter20/Assessments/ReadMeChp20.pdf -------------------------------------------------------------------------------- /Chapter20/Chp20-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate use of pImpl pattern 3 | // Note: this driver can also be used with non-pImpl Person class or pImpl with unique pointers -- works the same! 4 | // To compile: g++ -c PersonImpl.cpp 5 | // g++ -c Chp20-Ex1.cpp 6 | // g++ -o runme PersonImpl.o Chp20-Ex1.o (executable is in 'runme') 7 | 8 | #include 9 | #include "Person.h" 10 | 11 | using std::cout; // preferred to: using namespace std; 12 | using std::endl; 13 | 14 | constexpr int MAX = 3; 15 | 16 | int main() 17 | { 18 | Person *people[MAX] = { }; // initialized to nullptrs 19 | people[0] = new Person("Elle", "LeBrun", 'R', "Ms."); 20 | people[1] = new Person("Zack", "Moon", 'R', "Dr."); 21 | people[2] = new Person("Gabby", "Doone", 'A', "Dr."); 22 | 23 | // preferred looping style here: 24 | for (auto *individual : people) 25 | individual->Print(); 26 | 27 | for (auto *individual : people) 28 | delete individual; 29 | 30 | // less desirable looping style below 31 | /* 32 | for (int i = 0; i < MAX; i++) 33 | people[i]->Print(); 34 | 35 | for (int i = 0; i < MAX; i++) 36 | delete people[i]; 37 | */ 38 | 39 | return 0; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Chapter20/Chp20-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To demonstrate a simple smart pointer class 3 | // Note: This class still needs to decide how to handle copy constructor and assignment operator 4 | // That is, shallow copies/assignment (probably not), deep copies/assignment (maybe), or prohibit copies/assignment (likely) 5 | // To compile: g++ -c PersonImpl.cpp 6 | // g++ -c Chp20-Ex2.cpp 7 | // g++ -o runme PersonImpl.o Chp20-Ex2.o (executable is in 'runme') 8 | 9 | #include 10 | #include "Person.h" 11 | 12 | using std::cout; // preferred to: using namespace std; 13 | using std::endl; 14 | 15 | template 16 | class SmartPointer 17 | { 18 | private: 19 | Type *pointer = nullptr; // in-class initialization 20 | public: 21 | SmartPointer(Type *ptr = nullptr): pointer(ptr) { } // handles default constructor case as well 22 | virtual ~SmartPointer() { cout << "SmartPtr Destructor" << endl; delete pointer; } 23 | Type *operator->() { return pointer; } 24 | Type &operator*() { return *pointer; } 25 | }; 26 | 27 | int main() 28 | { 29 | SmartPointer p1(new int()); 30 | SmartPointer pers1(new Person("Renee", "Alexander", 'K', "Dr.")); 31 | 32 | *p1 = 100; 33 | cout << *p1 << endl; 34 | (*pers1).Print(); // or use: pers1->Print(); 35 | 36 | return 0; 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Chapter20/Person.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Person class header file for pImpl pattern (with raw pointers) 3 | // Note: not to worry, we'll next implement it with smart pointers! 4 | 5 | #ifndef _PERSON_H 6 | #define _PERSON_H 7 | 8 | using std::string; 9 | 10 | class Person 11 | { 12 | private: 13 | class PersonImpl; // forward declaration to nested class 14 | PersonImpl *pImpl = nullptr; // pointer to implementation of class 15 | protected: 16 | void ModifyTitle(const string &); 17 | public: 18 | Person(); // default constructor 19 | Person(const string &, const string &, char, const string &); 20 | Person(const Person &); // copy constructor 21 | virtual ~Person(); // virtual destructor 22 | // Notice, access functions are no longer inline (also hides implementation) 23 | const string &GetFirstName() const; 24 | const string &GetLastName() const; 25 | const string &GetTitle() const; 26 | char GetMiddleInitial() const; 27 | virtual void Print() const; 28 | virtual void IsA() const; 29 | virtual void Greeting(const string &) const; 30 | Person &operator=(const Person &); // overloaded assignment operator prototype 31 | }; 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /Chapter20/ReadMe: -------------------------------------------------------------------------------- 1 | The files in this directory correspond to full program examples from Chapter 20. Note that the pImpl pattern example using a unique pointer is in a subdirectory 'unique' 2 | -------------------------------------------------------------------------------- /Chapter20/original/Chp20-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate use of pImpl pattern 3 | // Note: this driver can also be used with non-pImpl Person class or pImpl with unique pointers -- works the same! 4 | // To compile: g++ -c PersonImpl.cpp 5 | // g++ -c Chp20-Ex1.cpp 6 | // g++ -o runme PersonImpl.o Chp20-Ex1.o (executable is in 'runme') 7 | 8 | #include 9 | #include "Person.h" 10 | 11 | using namespace std; 12 | 13 | const int MAX = 3; 14 | 15 | int main() 16 | { 17 | Person *people[MAX]; 18 | people[0] = new Person("Giselle", "LeBrun", 'R', "Ms."); 19 | people[1] = new Person("Zack", "Moon", 'R', "Dr."); 20 | people[2] = new Person("Gabby", "Doone", 'A', "Dr."); 21 | 22 | for (int i = 0; i < MAX; i++) 23 | people[i]->Print(); 24 | 25 | for (int i = 0; i < MAX; i++) 26 | delete people[i]; 27 | 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Chapter20/original/Chp20-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To demonstrate a simple smart pointer class 3 | // Note: This class still needs to decide how to handle copy constructor and assignment operator 4 | // That is, shallow copies/assignment (probably not), deep copies/assignment (maybe), or prohibit copies/assignment (likely) 5 | // To compile: g++ -c PersonImpl.cpp 6 | // g++ -c Chp20-Ex2.cpp 7 | // g++ -o runme PersonImpl.o Chp20-Ex2.o (executable is in 'runme') 8 | 9 | #include 10 | #include "Person.h" 11 | 12 | using namespace std; 13 | 14 | template 15 | class SmartPointer 16 | { 17 | private: 18 | Type *pointer; 19 | public: 20 | SmartPointer(Type *ptr = NULL) { pointer = ptr; } 21 | virtual ~SmartPointer() { cout << "SmartPtr Destructor" << endl; delete pointer; } 22 | Type *operator->() { return pointer; } 23 | Type &operator*() { return *pointer; } 24 | }; 25 | 26 | int main() 27 | { 28 | SmartPointer p1(new int()); 29 | SmartPointer pers1(new Person("Renee", "Alexander", 'K', "Dr.")); 30 | 31 | *p1 = 100; 32 | cout << *p1 << endl; 33 | (*pers1).Print(); // or use: pers1->Print(); 34 | 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Chapter20/original/Person.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Person class header file for pImpl pattern (with raw pointers) 3 | 4 | #ifndef _PERSON_H 5 | #define _PERSON_H 6 | 7 | class Person 8 | { 9 | private: 10 | class PersonImpl; // forward declaration to nested class 11 | PersonImpl *pImpl; // pointer to implementation of class 12 | protected: 13 | void ModifyTitle(const char *); 14 | public: 15 | Person(); // default constructor 16 | Person(const char *, const char *, char, const char *); 17 | Person(const Person &); // copy constructor 18 | virtual ~Person(); // virtual destructor 19 | // Notice, access functions are no longer inline (also hides implementation) 20 | const char *GetFirstName() const; 21 | const char *GetLastName() const; 22 | const char *GetTitle() const; 23 | char GetMiddleInitial() const; 24 | virtual void Print() const; 25 | virtual void IsA(); 26 | virtual void Greeting(const char *); 27 | Person &operator=(const Person &); // overloaded assignment operator prototype 28 | }; 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /Chapter20/original/ReadMe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Chapter20/original/unique/Chp20-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate use of pImpl pattern 3 | // Note: this driver can be used with non-pImpl Person class or pImpl class with raw pointers -- works the same! 4 | // To compile: g++ -c PersonImpl.cpp 5 | // g++ -c Chp20-Ex3.cpp 6 | // g++ -o runme PersonImpl.o Chp20-Ex3.o (executable is in 'runme') 7 | 8 | 9 | #include 10 | #include 11 | #include 12 | #include "Person.h" 13 | 14 | using namespace std; 15 | 16 | const int MAX = 3; 17 | 18 | int main() 19 | { 20 | Person *people[MAX]; 21 | people[0] = new Person("Giselle", "LeBrun", 'R', "Ms."); 22 | people[1] = new Person("Zack", "Moon", 'R', "Dr."); 23 | people[2] = new Person("Gabby", "Doone", 'A', "Dr."); 24 | 25 | for (int i = 0; i < MAX; i++) 26 | people[i]->Print(); 27 | 28 | for (int i = 0; i < MAX; i++) 29 | delete people[i]; 30 | 31 | return 0; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Chapter20/original/unique/Person.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Person class header file using a unique pointer to model association between Person and PersonImpl 3 | 4 | #ifndef _PERSON_H 5 | #define _PERSON_H 6 | #include 7 | 8 | class Person 9 | { 10 | private: 11 | class PersonImpl; // forward declaration to nested class 12 | std::unique_ptr pImpl; // pointer to implementation of class 13 | protected: 14 | void ModifyTitle(const char *); 15 | public: 16 | Person(); // default constructor 17 | Person(const char *, const char *, char, const char *); 18 | Person(const Person &); // copy constructor 19 | virtual ~Person(); // virtual destructor 20 | const char *GetFirstName() const; // { return firstName; } 21 | const char *GetLastName() const; // { return lastName; } 22 | const char *GetTitle() const; // { return title; } 23 | char GetMiddleInitial() const; // { return middleInitial; } 24 | virtual void Print() const; 25 | virtual void IsA(); 26 | virtual void Greeting(const char *); 27 | Person &operator=(const Person &); // overloaded assignment operator prototype 28 | }; 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /Chapter20/original/unique/ReadMe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Chapter20/unique/Chp20-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: To illustrate use of pImpl pattern - in this version, the implementation uses smart pointers! 3 | // Note: this driver can be used with non-pImpl Person class or pImpl class with raw pointers -- works the same! 4 | // However, the implementation of this version (Person.h and PersonImpl.cpp uses smart pointers) 5 | // To compile: g++ -c PersonImpl.cpp 6 | // g++ -c Chp20-Ex3.cpp 7 | // g++ -o runme PersonImpl.o Chp20-Ex3.o (executable is in 'runme') 8 | 9 | 10 | #include 11 | #include 12 | #include "Person.h" 13 | 14 | using std::cout; // preferred to: using namespace std; 15 | using std::endl; 16 | 17 | constexpr int MAX = 3; 18 | 19 | int main() 20 | { 21 | Person *people[MAX] = { }; // initialized to nullptrs 22 | people[0] = new Person("Giselle", "LeBrun", 'R', "Ms."); 23 | people[1] = new Person("Zack", "Moon", 'R', "Dr."); 24 | people[2] = new Person("Gabby", "Doone", 'A', "Dr."); 25 | 26 | // preferred looping style here: 27 | for (auto *individual : people) 28 | individual->Print(); 29 | 30 | for (auto *individual : people) 31 | delete individual; 32 | 33 | // less desirable looping style 34 | /* 35 | for (int i = 0; i < MAX; i++) 36 | people[i]->Print(); 37 | 38 | for (int i = 0; i < MAX; i++) 39 | delete people[i]; 40 | */ 41 | 42 | return 0; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Chapter20/unique/Person.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Person class header file using a unique pointer to model association between Person and PersonImpl 3 | 4 | #ifndef _PERSON_H 5 | #define _PERSON_H 6 | #include 7 | 8 | using std::string; 9 | 10 | class Person 11 | { 12 | private: 13 | class PersonImpl; // forward declaration to nested class 14 | std::unique_ptr pImpl; // pointer to implementation of class 15 | protected: 16 | void ModifyTitle(const string &); 17 | public: 18 | Person(); // default constructor 19 | Person(const string &, const string &, char, const string &); 20 | Person(const Person &); // copy constructor 21 | virtual ~Person(); // virtual destructor 22 | const string &GetFirstName() const; // { return firstName; } 23 | const string &GetLastName() const; // { return lastName; } 24 | const string &GetTitle() const; // { return title; } 25 | char GetMiddleInitial() const; // { return middleInitial; } 26 | virtual void Print() const; 27 | virtual void IsA() const; 28 | virtual void Greeting(const string &) const; 29 | Person &operator=(const Person &); // overloaded assignment operator prototype 30 | }; 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /Chapter20/unique/ReadMe: -------------------------------------------------------------------------------- 1 | The subdirectory 'unique' contains the pImpl pattern example using a unique pointer. 2 | -------------------------------------------------------------------------------- /Chapter21/Chp21-Ex1.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Brief demo of a unique pointer 3 | 4 | #include 5 | #include 6 | #include "Person.h" 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::unique_ptr; 11 | using std::make_unique; 12 | 13 | // We will create unique pointers, with and without using the make_unique (safe wrapper) interface 14 | 15 | int main() 16 | { 17 | unique_ptr p1(new int(100)); 18 | // equivalant to: 19 | // unique_ptr p1(new int()); 20 | // *p1 = 100; 21 | cout << *p1 << endl; 22 | 23 | unique_ptr pers1(new Person("Renee", "Alexander", 'K', "Dr.")); 24 | (*pers1).Print(); // or alternatively use: pers1->Print(); 25 | 26 | unique_ptr pers2; 27 | pers2 = move(pers1); // take over another unique pointer's resource 28 | pers2->Print(); 29 | 30 | auto pers3 = make_unique("Giselle", "LeBrun", 'R', "Ms."); 31 | pers3->Print(); 32 | 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Chapter21/Chp21-Ex2.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Brief demo of a shared pointer 3 | 4 | #include 5 | #include 6 | #include "Person.h" 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::shared_ptr; 11 | 12 | int main() 13 | { 14 | shared_ptr p1 = std::make_shared(100); 15 | // alternative to preferred, above line of code: 16 | // shared_ptr p1(new int(100)); 17 | 18 | shared_ptr p2; // currently uninitialized 19 | p2 = p1; // p2 points to the same memory as p1 20 | cout << *p1 << " " << *p2 << endl; 21 | 22 | shared_ptr pers1 = std::make_shared ("Gabby", "Doone", 'A', "Miss"); 23 | // alternative to preferred, above line of code: 24 | // shared_ptr pers1(new Person("Gabby", "Doone", 'A', "Miss")); 25 | 26 | shared_ptr pers2 = pers1; // notice we initialize with the valid address 27 | 28 | pers1->Print(); // or alternatively use: (*pers1).Print(); 29 | pers2->Print(); 30 | pers1->ModifyTitle("Dr."); 31 | pers2->Print(); 32 | 33 | cout << "Number of references: " << pers1.use_count() << endl; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Chapter21/Chp21-Ex3.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Brief demo of a weak pointer 3 | 4 | #include 5 | #include 6 | #include "Person.h" 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::weak_ptr; 11 | using std::shared_ptr; 12 | 13 | // Note: could also include: using std::make_shared; if you don't want to qualify use below with std:: 14 | 15 | int main() 16 | { 17 | shared_ptr pers1 = std::make_shared("Gabby", "Doone", 'A', "Miss"); 18 | // Above line is equivalanet to: 19 | // shared_ptr pers1(new Person("Gabby", "Doone", 'A', "Miss")); 20 | 21 | pers1->Print(); // or alternatively use: (*pers1).Print(); 22 | 23 | weak_ptr wpers1(pers1); // Downgrade pers1 to a weak pointer 24 | // wpers1->Print(); // note: weak pointer can not access the resource, must use a shared pointer to do so 25 | 26 | cout << "# references: " << pers1.use_count() << endl; 27 | cout << "# references: " << wpers1.use_count() << endl; 28 | 29 | shared_ptr pers2 = wpers1.lock(); // create a shared pointer to the resource 30 | // shared_ptr pers2(wpers1.lock()); // same as line above - alternate initialization 31 | pers2->Print(); 32 | 33 | pers2->ModifyTitle("Dr."); 34 | pers2->Print(); 35 | 36 | cout << "# references: " << pers1.use_count() << endl; 37 | cout << "# references: " << wpers1.use_count() << endl; 38 | cout << "# references: " << pers2.use_count() << endl; 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Chapter21/Person.cpp: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Basic implementation of Person class 3 | 4 | #include 5 | #include 6 | #include "Person.h" 7 | 8 | using std::cout; // preferred to: using namespace std; 9 | using std::endl; 10 | using std::string; 11 | 12 | 13 | // Remember, we're using system provided default constructor (and in-class initialization) 14 | 15 | // Alternate constructor 16 | Person::Person(const string &fn, const string &ln, char mi, const string &t) : 17 | firstName(fn), lastName(ln), middleInitial(mi), title(t), greeting("Hello") 18 | 19 | { 20 | } 21 | 22 | // We're using default copy constructor, but if we wrote it, it would look like: 23 | /* 24 | Person::Person(const Person &p) : firstName(p.firstName), lastName(p.lastName), 25 | middleInitial(p.middleInitial), title(p.title), greeting(p.greeting) 26 | { 27 | } 28 | */ 29 | 30 | // Demonstrating simple overloaded operator= implementation 31 | Person &Person::operator=(const Person &p) 32 | { 33 | // make sure we're not assigning an object to itself 34 | if (this != &p) 35 | { 36 | // Note: there's no dynamically allocated data members, so implementing = is straightforward 37 | firstName = p.firstName; 38 | lastName = p.lastName; 39 | middleInitial = p.middleInitial; 40 | title = p.title; 41 | greeting = p.greeting; 42 | } 43 | return *this; // allow for cascaded assignments 44 | } 45 | 46 | Person::~Person() 47 | { 48 | cout << "Person destructor" << endl; 49 | } 50 | 51 | void Person::ModifyTitle(const string &newTitle) 52 | { 53 | title = newTitle; 54 | } 55 | 56 | void Person::SetGreeting(const string &newGreeting) 57 | { 58 | greeting = newGreeting; 59 | } 60 | 61 | 62 | void Person::Print() const 63 | { 64 | cout << title << " " << firstName << " " << lastName << endl; 65 | } 66 | -------------------------------------------------------------------------------- /Chapter21/Person.h: -------------------------------------------------------------------------------- 1 | // (c) Dorothy R. Kirk. All Rights Reserved. 2 | // Purpose: Person class header file 3 | 4 | #ifndef _PERSON_H 5 | #define _PERSON_H 6 | 7 | using std::string; 8 | 9 | class Person 10 | { 11 | private: 12 | string firstName; 13 | string lastName; 14 | char middleInitial = '\0'; // in-class initialization -- value to be used in default constructor 15 | string title; // Mr., Ms., Mrs., Miss, Dr., etc. 16 | string greeting; 17 | public: 18 | Person() = default; // default constructor 19 | Person(const string &, const string &, char, const string &); // alternate constructor 20 | // Remember, it is not necessary to prototype the default copy constructor 21 | // Person(const Person &) = default; // copy constructor 22 | Person &operator=(const Person &); // overloaded assignment operator 23 | virtual ~Person(); // virtual destructor 24 | const string &GetFirstName() const { return firstName; } // firstName returned as reference to const string 25 | const string &GetLastName() const { return lastName; } // so is lastName (via implicit cast) 26 | const string &GetTitle() const { return title; } 27 | char GetMiddleInitial() const { return middleInitial; } 28 | void ModifyTitle(const string &); 29 | void SetGreeting(const string &); 30 | virtual const string &Speak() { return greeting; } // note return type of const string & (we're no longer returning a literal) 31 | virtual void Print() const; 32 | }; 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /Chapter21/ReadMe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Modified MIT License 2 | 3 | Copyright (c) 2020 - 2022. Dorothy R. Kirk. All Rights Reserved. 4 | 5 | Permission is hereby granted, free of charge, to persons purchasing 6 | Demystified Object-Oriented-Programming with C++ book or e-book to utilize the 7 | example programs contained herein for individual learning. This software may 8 | not be used as a basis to create course wear (whether it be for business or 9 | educational use), or other books. 10 | 11 | Personal use of the software is subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | --------------------------------------------------------------------------------