140 likes | 155 Views
Constructing Objects. Classes – not for education only (or are they) OR Political correctness is not for objects. Typedef. Aliasing types (or classes) typedef int Age; typedef string Name; typedef float Distance_in_Meters; typedef float Money_in_Ks;// dollars. Classes.
E N D
Constructing Objects Classes– not for education only (or are they) OR Political correctness is not for objects
Typedef • Aliasing types (or classes) typedef int Age; typedef string Name; typedef float Distance_in_Meters; typedef float Money_in_Ks;//dollars Gene Itkis: cs112, lec.3
Classes • Classes are “data types” • Programmer-defined • Pre-defined: • int, float, bool, etc. – are all classes • Every object must belong to a class Gene Itkis: cs112, lec.3
A class is born… class ClassName{ public: // constructors;member functions/fields; protected: data fields/functions;private: data fields/functions;}; ClassName VarName; //instantiation Gene Itkis: cs112, lec.3
Protecting Privacy • Public • The Interface – accessible by non-members and members alike • Private • Accessible only by members • Protected • Same as private, except for friends • Real classes should not have public variables– they would have public methods (functions) Gene Itkis: cs112, lec.3
Class Action Class Action { public: bool Sue(Name Target, Money_in_Ks Ripoff) {…}; //function def skipped protected: Money_in_Ks Bribe; }; Action MyLawyer; Gene Itkis: cs112, lec.3
Addressing Class Methods • How to address members of the class objects: MyLawyer.Sue(“Mr.BigBucks”, 100000.0); • My Lawer’s “friends” (from “BigBucks”) could access MyLawyer.Bribe = 100000.1; Gene Itkis: cs112, lec.3
Example: Pair class pairOfInts { public: int firstInt; int secondInt; }; pairOfInts GameScore; GameScore.firstInt=1; GameScore.secondInt=4; //typical Red Sox score Gene Itkis: cs112, lec.3
Example: Instructor class instructor { public: string name; string course; int num_students=0; }; Gene Itkis: cs112, lec.3
Example 1 revisited class instructor { public: string name; string course; int numStudents(student studentList[100]) { return countStudents( StudentList, course ); } // countStudents() defined elsewhere }; Gene Itkis: cs112, lec.3
Example: Pair revisited(on board) class pairOfInts { public: int firstInt; int secondInt; }; pairOfInts GameScore; GameScore.firstInt=1; GameScore.secondInt=4; //typical Red Sox score Gene Itkis: cs112, lec.3
Crypto example • Baby RSA class RSA { public: int encrypt(int clear_text) { return pow(clear_text, pub_key)%modulus; } private: int modulus, pub_key;} RSA GeneRSA; … Cipher_text = GeneRSA.encrypt(message); Gene Itkis: cs112, lec.3
Pointing at Objects float MyMoney; float* pMyMoney=&MyMoney; //ptr to //addr of Student S; Student* pS=&S; (*pS).gpa = 3.5; // object pointed at pS->gpa = 3.5 // same as above Gene Itkis: cs112, lec.3
More on classes – in later classes To be continued…