1 / 47

CIS 4930 Application Development Using C++ Dr. Kun Suk Kim CISE Department, University of Florida

CIS 4930 Application Development Using C++ Dr. Kun Suk Kim CISE Department, University of Florida. Inheritance. Objectives. Inheritance Basics Derived classes, with constructors protected: qualifier Redefining member functions Non-inherited functions Programming with Inheritance

john-ross
Télécharger la présentation

CIS 4930 Application Development Using C++ Dr. Kun Suk Kim CISE Department, University of Florida

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CIS 4930Application Development Using C++Dr. Kun Suk KimCISE Department, University of Florida Inheritance

  2. Objectives • Inheritance Basics • Derived classes, with constructors • protected: qualifier • Redefining member functions • Non-inherited functions • Programming with Inheritance • Assignment operators and copy constructors • Destructors in derived classes • Multiple inheritance

  3. Introduction to Inheritance • Object-oriented programming • Powerful programming technique • Provides abstraction dimension calledinheritance • General form of class is defined • Specialized versions then inherit properties ofgeneral class • And add to it/modify it’s functionality for it’sappropriate use

  4. Inheritance Basics • New class inherited from another class • Base class • ‘General’ class from which others derive • Derived class • New class • Automatically has base class’s: • Member variables • Member functions • Can then add additional member functionsand variables

  5. Example • Consider example: Class of ‘Person’

  6. Interface for Person Class – person.h #ifndef PERSON_H #define PERSON_H #include <string> using std::string; namespace namePerson { class Person { public: Person( ); Person(string theName, string theSsn); string getName( ) const; string getSsn( ) const; void setName(string theName); void setSsn(string theSsn); void printStatus( ) const; private: string name; string ssn; }; }//namePerson #endif //PERSON_H

  7. Implementation for Person Classes - person.cpp #include <string> #include <cstdlib> #include <iostream> #include "person.h" using std::string; using std::cout; namespace namePerson { Person::Person( ) : name("-"), ssn("-") { } Person::Person(string theName, string theSsn) : name(theName), ssn(theSsn) { } string Person::getName( ) const { return name; }

  8. Implementation for Person Classes - person.cpp string Person::getSsn( ) const { return ssn; } void Person::setName(string theName) { name = theName; } void Person::setSsn(string theSsn) { ssn = theSsn; } void Person::printStatus() const { cout << "printStatus called for undifferenctiated person.\n"; cout << "Abnormally exit the program.\n"; exit(1); } }//namePerson

  9. Derived Classes • Persons are composed of: • Students • Faculties • Each is ‘subset’ of Person

  10. Derived Classes • Don’t ‘need’ type of generic ‘person’ • Since no one’s just an ‘person’ • General concept of person helpful! • All have names • All have social security numbers • Associated functions for these ‘basics’ aresame among all persons • So ‘general’ class can contain all these‘things’ about persons

  11. Person Class • Many members of ‘person’ class applyto all types of persons • Accessor functions • Mutator functions • Most data items: • SSN • Name • We won’t have ‘objects’ of this class,however

  12. Person Class • Consider printStatus() function: • Will always be ‘redefined’ in derived classes • So different person types can havedifferent status • Makes no sense really for ‘undifferentiated’person • So function printStatus() in Person classsays just that • Error message stating “printStatus called forundifferentiated person. Abnormally exit…”

  13. Deriving from Person Class • Derived classes from Person class: • Automatically have all member variables • Automatically have all member functions • Derived class said to ‘inherit’ membersfrom base class • Can then redefine existing membersand/or add new members

  14. Interface for Student Class – student.h #ifndef STUDENT_H #define STUDENT_H #include <string> #include "person.h" using std::string; namespace namePerson { class Student : public Person { public: Student( ); Student(string theName, string theSsn, int theGrade, double theGpa); void setGrade(int theGrade); int getGrade( ) const; void setGpa(double theGpa); double getGpa( ) const; void printStatus( ) ; private: int grade; double gpa; }; }//namePerson #endif //STUDENT_H

  15. Implementation for Student Class – student.cpp #include <string> #include <iostream> #include "student.h" using std::string; using std::cout; using std::endl; namespace namePerson { Student::Student( ) : Person( ), grade(0), gpa(0.0) { } Student::Student(string theName, string theSsn, int theGrade, double theGpa) : Person(theName, theSsn), grade(theGrade), gpa(theGpa) { } void Student::setGrade(int theGrade) { grade = theGrade; }

  16. Implementation for Student Class – student.cpp int Student::getGrade( ) const { return grade; } void Student::setGpa(double theGpa) { gpa = theGpa; } double Student::getGpa( ) const { return gpa; } void Student::printStatus( ) { cout << "Name: " << getName( ) << endl << "SSN Number: " << getSsn( ) << endl << "Student Records" << " Grade: " << getGrade() << " GPA: " << getGpa() << endl; } }//namePerson

  17. Interface for Faculty Class – faculty.h #ifndef FACULTY_H #define FACULTY_H #include <string> #include "person.h" using std::string; namespace namePerson { class Faculty : public Person { public: Faculty( ); Faculty (string theName, string theSsn, string theArea); string getArea( ) const; void setArea(string theArea); void printStatus( ); private: string area; }; }//namePerson #endif //FACULTY_H

  18. Implementation for Faculty Class – faculty.cpp #include <iostream> #include <string> #include "faculty.h" using std::string; using std::cout; using std::endl; namespace namePerson { Faculty::Faculty( ) : Person( ), area("-") { } Faculty::Faculty(string theName, string theSsn, string theArea) : Person(theName, theSsn), area(theArea) { } string Faculty::getArea() const { return area; }

  19. Implementation for Faculty Class – faculty.cpp void Faculty::setArea(string theArea) { area = theArea; } void Faculty::printStatus( ) { cout << "Name: " << getName( ) << endl << "SSN Number: " << getSsn( ) << endl << "Faculty Records" << endl << " Area: " << getArea() << endl; } }//namePerson

  20. Driver Program #include <iostream> #include "student.h" #include "faculty.h" using std::cout; using std::endl; using namePerson::Student; using namePerson::Faculty; int main( ) { Student st; st.setName("Study Hard"); st.setSsn("111-22-3333"); st.setGrade(4); st.setGpa(3.5); st.printStatus( ); Faculty prof("Prof. WorkHard", "444-55-6666", "C++"); prof.printStatus( ); return 0; } Name: Study Hard SSN Number: 111-22-3333 Student Records Grade: 4 GPA: 3.5 Name: Prof. WorkHard SSN Number: 444-55-6666 Faculty Records Area: C++

  21. Student Class Interface • Note definition begins same as any other • #ifndef structure • Includes required libraries • Also includes person.h • And, the heading:class Student : public Person{ … • Specifies ‘publicly inherited’ from Personclass

  22. Student Class Additions • Derived class interface only lists new or‘to be redefined’ members • Since all others inherited are already defined • i.e.: ‘all’ persons have ssn and name • Student adds: • Constructors • grade, gpa member variables • setGrade(), getGrade(), setGpa(), getGpa()member functions

  23. Student Class Redefinitions • Student redefines: • printStatus() member function • This ‘overrides’ the printStatus() functionimplementation from Person class • Its definition must be in Student class’s implementation • As do other member functions declared inStudent’s interface • New and ‘to be redefined’

  24. Inheritance Terminology • Common to simulate family relationships • Parent class • Refers to base class • Child class • Refers to derived class • Ancestor class • Class that’s a parent of a parent … • Descendant class • Opposite of ancestor

  25. Constructors in Derived Classes • Base class constructors are NOTinherited in derived classes! • But they can be invoked within derived classconstructor • Which is all we need! • Base class constructor must initialize allbase class member variables • Those inherited by derived class • So derived class constructor simply calls it • ‘First’ thing derived class constructor does

  26. Derived Class Constructor Example • Consider syntax for Student constructor:Student:: Student(string theName, string theSsn, int theGrade, double theGpa) : Person(theName, theSsn), grade(theGrade), gpa(theGpa) { } • Portion after : is ‘initialization section’ • Includes invocation of Person constructor

  27. Another Student Constructor • A second constructor:Student::Student() : Person(), grade(0), gpa(0.0) { } • Default version of base class constructoris called (no arguments) • Should always invoke one of the baseclass’s constructors

  28. Constructor: No Base Class Call • Derived class constructor should alwaysinvoke one of the base class’s constructors • If you do not: • Default base class constructor automaticallycalled • Equivalent constructor definition:Student::Student(): grade(0), gpa(0.0) { }

  29. Pitfall: Base Class Private Data • Derived class ‘inherits’ private membervariables • But still cannot directly access them • Not even through derived class memberfunctions! • Private member variables can ONLY beaccessed ‘by name’ in member functionsof the class they’re defined in

  30. Pitfall: Base Class Private Member Functions • Same holds for base class memberfunctions • Cannot be accessed outside interface andimplementation of base class • Not even in derived class member functiondefinitions

  31. Pitfall: Base Class Private Member Functions Impact • Larger impact here vs. member variables • Member variables can be accessed indirectlyvia accessor or mutator member functions • Member functions simply not available • This is ‘reasonable’ • Private member functions should be simply‘helper’ functions • Should be used only in class they’re defined

  32. The protected: Qualifier • New classification of class members • Allows access ‘by name’ in derived class • But nowhere else • Still no access ‘by name’ in other classes • In class it’s defined  acts like private • Considered ‘protected’ in derived class • To allow future derivations • Many feel this ‘violates’ information hiding

  33. Redefinition of Member Functions • Recall interface of derived class: • Contains declarations for new memberfunctions • Also contains declarations for inheritedmember functions to be changed • Inherited member functions NOT declared: • Automatically inherited unchanged • Implementation of derived class will: • Define new member functions • Redefine inherited functions as declared

  34. Redefining vs. Overloading • Very different! • Redefining in derived class: • SAME parameter list • Essentially ‘re-writes’ same function • Overloading: • Different parameter list • Defined ‘new’ function that takes differentparameters • Overloaded functions must have differentsignatures

  35. A Function’s Signature • Definition of a ‘signature’: • Function’s name • Sequence of types in parameter list • Including order, number, types • Signature does NOT include: • Return type • const keyword • &

  36. Accessing Redefined Base Function • When redefined in derived class, baseclass’s definition not ‘lost’ • Can specify it’s use:Person p;Student s; p.printStatus();  calls Person’s printStatus function s.printStatus();  calls Student’s printStatus function s.Person::printStatus();  Calls Person’s printStatus function! • Not typical here, but useful sometimes

  37. Functions Not Inherited • All ‘normal’ functions in base class areinherited in derived class • Exceptions: • Constructors (we’ve seen) • Destructors • Copy constructor • But if not defined, generates ‘default’ one • Recall need to define one for pointers! • Assignment operator • If not defined  default

  38. Assignment Operators and Copy Constructors • Recall: overloaded assignment operatorsand copy constructors NOT inherited • But can be used in derived class definitions • Typically MUST be used! • Similar to how derived class constructorinvokes base class constructor

  39. Assignment Operator Example • Given ‘Derived’ is derived from ‘Base’:Derived& Derived::operator =(const Derived & rightSide){ Base::operator =(rightSide); …} • Notice code line • Calls assignment operator from base class • This takes care of all inherited member variables • Would then set new variables from derivedclass…

  40. Copy Constructor Example • Consider:Derived::Derived(const Derived& Object) : Base(Object), …{…} • After : is invocation of base copyconstructor • Sets inherited member variables of derivedclass object being created • Note Object is of type Derived; but it’s also oftype Base, so argument is valid

  41. Destructors in Derived Classes • If base class destructor functions correctly • Easy to write derived class destructor • When derived class destructor is invoked: • Automatically calls base class destructor! • So no need for explicit call • So derived class destructors need only beconcerned with derived class variables • And any data they ‘point’ to • Base class destructor handles inherited dataautomatically

  42. Destructor Calling Order • Consider:class B derives from class Aclass C derives from class B A  B  C • When object of class C goes out of scope: • Class C destructor called first • Then class B destructor called • Finally class A destructor is called • Opposite of how constructors are called

  43. “Is a” vs. “Has a” Relationships • Inheritance • Considered an “Is a” class relationship • e.g.: An Student “is a” Person • A Convertible “is a” Automobile • A class contains objects of another classas it’s member data • Considered a “Has a” class relationship • e.g.: One class “has a” object of anotherclass as it’s data

  44. Protected and Private Inheritance • New inheritance ‘forms’ • Both are rarely used • Protected inheritance:class Faculty : protected Person{…} • Public members in base class becomeprotected in derived class • Private inheritance:class Faculty : private Person{…} • All members in base class become privatein derived class

  45. Multiple Inheritance • Derived class can have more than onebase class! • Syntax just includes all base classesseparated by commas:class derivedMulti : public base1, base2{…} • Possibilities for ambiguity are endless! • Dangerous undertaking! • Some believe should never be used • Certainly should only be used be experiencedprogrammers!

  46. Summary 1 • Inheritance provides code reuse • Allows one class to ‘derive’ from another,adding features • Derived class objects inherit members ofbase class • And may add members • Private member variables in base classcannot be accessed ‘by name’ in derived • Private member functions are not inherited

  47. Summary 2 • Can redefine inherited member functions • To perform differently in derived class • Protected members in base class: • Can be accessed ‘by name’ in derived classmember functions • Overloaded assignment operator notinherited • But can be invoked from derived class • Constructors are not inherited • Are invoked from derived class’s constructor

More Related