Classes and Inheritance

718 views

Published on

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
718
On SlideShare
0
From Embeds
0
Number of Embeds
14
Actions
Shares
0
Downloads
20
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Classes and Inheritance

  1. 1. More on Classes and Inheritance
  2. 2. Reusing Code Don't reinvent the wheel: reuse your code or somebody else's code whenever possible. Ideal is to reuse code with no modification. Many years back programmers realized that the same code gets written over and over again. C++ addresses this issue with inheritance and classes.
  3. 3. Derived Classes You can create classes that are subtypes of existing classes. You can build up from an existing classes to add (or subtract) whatever behavior you need. This is one of the central features of OOP - object oriented programming.
  4. 4. Derived Class Example Derived Classes Base Class class RCC_Student class RCC_Person { class RCC_Employee string get_SS(); class RCC_Teacher bool get_library_hold(); RCC_Person(string name); // other stuff };
  5. 5. Derived Class Syntax: Single Colon : class RCC_Person class RCC_Student: { public RCC_Person string get_SS(); { string get_class() {} bool get_library_hold(); int get_tuition() {} }; RCC_Person(string name); class RCC_Employee: // other stuff public RCC_Person }; { int get_salary() {} };
  6. 6. Derived Class Syntax class human { string last_name; public: string get_last_name(); }; class american: public human { void serve_hamburger(); }; The addition of quot;:public humanquot; makes american a derived class of human.
  7. 7. Class assignment (I don't mean HW) Base class: RCC_Person derived classes: RCC_Student, RCC_Employee pointers to student or employee objects would be pointers to the person type object: RCC_Person *personPtr; personPtr = new RCC_Student(quot;your name herequot;); -or- personPtr = new RCC_Employee(quot;my name herequot;); This pointer can accept any class derived from RCC_Person.
  8. 8. Class Assignment The assignment does not need to be of pointer objects. It could be the object itself. RCC_Person personVar; RCC_Employee employeeVar; RCC_Student studentVar; personVar = employeeVar; -or- personVar = studentVar; -or- personVar = RCC_Person(quot;enter name herequot;);
  9. 9. RCC_Person Example vector<RCC_Person *> people; RCC_Student * student = new RCC_Student(quot;Joe Coolquot;); RCC_Employee * employee = new RCC_Employee(quot;Prof. Lilomanquot;); people.push_back(student); people.push_back(employee);
  10. 10. RCC_Person Example Say the RCC_Student class has a function called get_gpa. This function does not pertain to employees. It belongs in the RCC_student class. int gpa; gpa = student.get_grade();
  11. 11. RCC_Person Example remember the vector of people: vector<RCC_Person *> people; RCC_Person person = *people[index]; Can we do this? gpa = person.get_gpa(); Thoughts from the class?
  12. 12. RCC_Person example remember the vector of people: vector<RCC_Person *> people; RCC_Person person = *people[index]; Can we do this? gpa = person.get_gpa(); NO!
  13. 13. Pointer syntax -> remember the vector of people: vector<RCC_Person *> people; RCC_Person person = *people[index]; You don't need to take the person out of the people[index] pointer. Arrow syntax -> combines * and .
  14. 14. -> Syntax for Pointers Arrow syntax -> combines * and . vector<RCC_Person *> people; RCC_Person * pPtr = people[index]; // copied the pointer, not the content But that's a pointer to the person, not the person. How to get to the functions? string name; name = person->get_last_name();
  15. 15. -> Syntax for Pointers cout << person->get_last_name() << endl; is the same as: cout << (*person) .get_last_name() << endl;
  16. 16. Back to RCC_person example remember the vector of people: vector<RCC_Person *> people; RCC_Person pPtr = people[index]; Can we do this? gpa = pPtr -> get_gpa(); NO! We don't know that the person is a student.
  17. 17. RCC_Person Example vector<RCC_Person *> people; RCC_Person pPtr = people[index]; Can't do this: gpa = pPtr -> get_gpa(); This person might be a student but we have no guarantee, since the vector is a vector of RCC_Person.
  18. 18. Casting: Dynamic Casting: New Syntax This class is a polymorphic class because the function is declared virtual: class one { public: one(); virtual string get_one(); }; one::one(){} string one::get_one() { return quot;onequot;; }
  19. 19. Virtual Functions: New Syntax C++ virtual function is: • A member function of a class Declared with virtual keyword • • Usually has a different functionality in the derived class • A function call is resolved at run-time C++ Virtual Function - Reasons: The most prominent reason why a C++ virtual function will be used is to have a different functionality in the derived class.
  20. 20. Derived Class: Dynamic Casting class two : public one { public: two(); string get_two(); }; two::two(){} string two::get_two() { return quot;twoquot;; }
  21. 21. Dynamic Casting Example vector <one *> onesVec; two * newTwo = new two(); onesVec.push_back(newTwo); one * ptOne = onesVec[0]; two * ptTwo = dynamic_cast<two *> (ptOne); msg = ptTwo -> get_one() cout << << quot; quot; << ptTwo -> get_two() << endl;
  22. 22. RCC_Person Example Without the virtual key word in front of the get_info function: the get_info functions in each of RCC_Student and RCC_Employee DO NOT override the get_info function in RCC_Person. Since the vector is a vector RCC_Person, the get_info function in RCC_Person wins.
  23. 23. RCC_Person Example With the quot;virtualquot; key word, even though it's a vector of RCC_Person, When Joe Cool Student goes into the vector, the RCC_Student get_info function wins. When Prof. Liloman goes into the vector, the RCC_Employee get_info function wins.
  24. 24. RCC_Person Example With the quot;virtualquot; key word, even though it's a vector of RCC_Person, When Joe Cool Student goes into the vector, the RCC_Student get_info function wins. When Prof. Liloman goes into the vector, the RCC_Employee get_info function wins. What would happen if it was a vector of RCC_Student? thoughts from the class
  25. 25. Prof. Stroustrup's definition of Object Oriented programming derived classes, or, inheritance. Build or reuse base classes and then create more classes built up from those classes virtual functions If a function is defined for more than one type of class, the correct function is invoked at run time. encapsulation some functions are public, but others are private
  26. 26. Dynamic Polymorphism Polymorphism Poly - many morph - body shape ie Ovid's Metamorphosis quot;Beyond Shapequot; We remember what dynamic means in the context of programming, right? Thoughts from class.
  27. 27. Polymorphism Poly - many morph - body shape ie Ovid's Metamorphosis quot;Beyond Shapequot; We remember what dynamic means in the context of programming, right? Determined at RUN TIME!
  28. 28. Different Shapes at Run Time How do you get different shapes at run time, ie depending on the data? using virtual methods in your classes. If it's a student's record coming in, then use the appropriate student functions. If it's an employee's record coming in, use the employee functions.
  29. 29. Different Shapes at Compile Time How do you do that? Templates: More new stuff around classes.
  30. 30. Templates Example: Function Template template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i = 5; int j = 6; int k; double l = 10.5; double m = 5; double n; k = GetMax<int>(i, j); n = GetMax<double>(l, m); cout << k << endl; cout << n << endl; return 0; }
  31. 31. Function templates: Syntax template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } T GetMax (T a, T b) This line declares a function that returns type T,and takes two parameters of type T. T result;This line declares a variable of type T All of that is the usual.
  32. 32. Function templates: Syntax The start of the function is slightly different: template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } The template keyword and the angle brackets declare that this is a function template. The name T represents a type that is left unspecified.T could be replaced with quot;junkquot;.
  33. 33. Function templates: Syntax When you call a function that is a template, the syntax is slightly different. int main () { int i = 5; int j = 6; int k; double l = 10.5; double m = 5; double n; k = GetMax<int>(i, j); n = GetMax<double>(l, m);... You need to tell the compiler just what the mystery type is. Notice the GetMax<int> and GetMax<double>
  34. 34. Function Templates Notice that this example would only work for types that have a valid meaning for < and other comparisons. If you created some type that did not have a meaning for > and <, and you tried to use this function, you would get an error.
  35. 35. Meaningless Code template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); }class noComparison {};int main () { int i = 5, j = 6, k; double l = 10.5, m = 5, n; noComparison p, q, r; k = GetMax<int>(i, j); n = GetMax<double>(l, m); r = GetMax<noComparison>(p, q); // from here this looks right, but it's not.Thoughts?
  36. 36. Class Templates In combination with a class: template <class T> class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } }; Here the template syntax is used before the class.T is any valid type.The object will have an array of 2 elements of whatever valid type the constructor gets.
  37. 37. Class Templates Let's draw out this example: declare the class template <class T> class mypair { T values [2]; public: mypair (T first, T second); T getmax (); };
  38. 38. Class Templates Functions in the class template <class T> mypair<T>::mypair (T first, T second) { values[0]=first; values[1]=second; } template <class T> T mypair<T>::getmax() { T retval; // more new syntax: the ? retval = values[0] > values[1] ? values[0] : values[1];
  39. 39. Class Templates In the calling code: mypair <int> myobject (100, 75); cout << quot;Max object in my object with ints is quot; << myobject.getmax() << endl; mypair <string> mySobj(quot;aaaquot;, quot;bbbquot;); cout << quot;Max object in my object with strings is quot; << mySobj.getmax() << endl;
  40. 40. Templates: What the compiler does Templates are not normal functions or classes. They are compiled on demand: the code of a template function is not compiled until an instantiation with specific template arguments is required. At that moment, when a call is made, the compiler generates a function specifically for those arguments from the template.
  41. 41. Notes on Classes: More Syntax Classes defined with struct and unionClasses can be defined not only with keyword class, but also with keywords struct and union. The concepts of class and data structure are so similar that both keywords (struct and class) can be used in C++ to declare classes (i.e. structs can also have function members in C++, not only data members).
  42. 42. Notes on Classes: More Syntax The only difference between struct and class: Members of classes declared with the keyword struct have public access by default. Members of classes declared with the keyword class have private access by default.
  43. 43. Class: more syntax The keyword thisThe keyword this represents a pointer to the object whose member function is being executed. It is a pointer to the object itself. In the functions inside of a class, you can refer to that same object with quot;thisquot;.
  44. 44. Class Syntax: Static members A class can contain static members, either data or functions.Static data members of a class are also known as quot;class variablesquot;, because there is only one unique value for all the objects of that same class. Their content is not different from one object of this class to another. What? Yes. For all objects of that type, there is only one value.
  45. 45. Static members: an example remember the book class? We could have counted how many books were created with this code: class Book { public: static int n; // this is valid syntax, remember from way back Book () { n++; }; }; int Book::n=0; int main () { Book oneBook; Book bookArray[5]; Book * bookPtr = new Book; cout << quot;How many books are there, oneBook? quot;<< oneBook.n << endl; cout << quot;What say you, bookPtr? quot;<< bookPtr -> n << endl; return ok; }
  46. 46. Encapsulation What does that mean for programming? What does Stroustrup mean? Here's some of what wikipedia said as of Monday! encapsulation is the hiding of the internal mechanisms  and data structures of a software component behind a  defined interface You create your class, and you give the declarations portion to however may want to use your class. But the details of how you defined your class, (the meat) is not visible to others. in such a way that users of the component (other pieces of software) only need to know what the component does, and cannot make themselves dependent on the details of how it
  47. 47. Encapsulation: Clock Analogy E nc a ps ula ting s oftwa re b e h ind a n interface m imic s th e be h a vior a nd inte ra c tions of objects in th e re a l world: An a la rm c loc k is a re a l-world object a nyb ody c a n us e a nd unde rs ta nd.  Th e y c a n unde rs ta nd th e provide d interface(buttons a nd s c re e n), with out h a ving to unde rs ta nd e ve ry pa rt ins ide of it.  If you re pla c e d th e c loc k with a diffe re nt mode l, th e pe rs on c ould c ontinue to us e it in th e s a me wa y if th e  interface works th e s a me .
  48. 48. Encapsulation: in Object Oriented Programming The interface to a class is defined by its public methods, while its internal state is represented by private data. E nc a ps ula tion a ls o prote c ts th e inte g rity of th e c om pone nt. Us e rs c a nnot s e t th e inte rna l da ta of th e c om pone nt into a n inva lid or inc ons is te nt s ta te .
  49. 49. Encapsulation The users of the component (other pieces of software) only need to know what the component does. They or it cannot make themselves dependent on the details of how the code does its job. The purpose is to achieve potential for change: the internal mechanisms of the component can be improved without impact on other components, or the component can be replaced with a different one that supports the same public interface.

×