// Ch. 12 Demo Program #3
// Mr. Minich // purpose - to illustrate the use of a struct and a user-defined function
#include <iostream.h> #include "M:\C++ Programming\AP classes\apstring.h" struct Student { apstring name; int gradeLevel; char grade; }; void getNameAndGradeLevel(Student &); int main() { Student teachersPet; Student classHacker;
getNameAndGradeLevel(teachersPet); getNameAndGradeLevel(classHacker); cout << "The teachers pet's grade is " << teachersPet.grade << endl; cout << "The class clown's grade is " << classHacker.grade << endl; return 0; } void getNameAndGradeLevel(Student & aStudent) { cout << "Enter a name and grade level: "; cin >> aStudent.name; cin >> aStudent.gradeLevel; if (aStudent.name == "Mitnick") { aStudent.grade = 'A'; } }
// The lazy teacher may have asked the class hacker to write the user-defined function getNameAndGradeLevel. // The class hacker (Kevin Mitnick) realizes that he had a chance to change the value of the member variable grade so // he added the if statement to the getNameAndGradeLevel function to give himself an A. // The teacher could have protected the grade member variable by placing it into the private partition of a struct. // struct Student // { // string name; // int gradeLevel;
// // private: // char grade; // };
// // Now the hacker's assignment statement would cause a compile error and not be allowed. Actually, the private partition // of a struct definition is not meant to be used to keep hackers from accessing certain variables (i.e. data) but // rather professional programmers like to protect themselves from accidentally changing certain member variables // so they protect them in this way.