inheritance polymorphism
play

Inheritance & Polymorphism Mark Redekopp 2 Example Code $ - PowerPoint PPT Presentation

1 EE 355 Unit 15 Inheritance & Polymorphism Mark Redekopp 2 Example Code $ wget http://ee.usc.edu/~redekopp/ee355/code/coninit.cpp $ make coninit 3 Consider this Struct/Class Examine this struct /class definition #include


  1. 1 EE 355 Unit 15 Inheritance & Polymorphism Mark Redekopp

  2. 2 Example Code • $ wget http://ee.usc.edu/~redekopp/ee355/code/coninit.cpp • $ make coninit

  3. 3 Consider this Struct/Class • Examine this struct /class definition… #include <string> #include <vector> using namespace std; struct Student { string name; int id; vector<double> scores; // say I want 10 test scores per student string name }; int id scores int main() { Student s1; }

  4. 4 Composite Objects • Fun Fact: Memory for an object comes alive before the code for the constructor starts at the first curly brace '{' #include <string> #include <vector> using namespace std; struct Student { string name; int id; vector<double> scores; string name // say I want 10 test scores per student int id Student() /* mem allocated here */ scores { // Can I do this to init. members? name("Tommy Trojan"); id = 12313; scores(10); } }; int main() { Student s1; }

  5. 5 Composite Objects • You cannot call constructors on data members once the constructor has started (i.e. passed the open curly '{' ) – So what can we do??? Use assignment operators (less efficient) or use constructor initialization lists! #include <string> #include <vector> using namespace std; struct Student { string name string name; int id int id; vector<double> scores; scores // say I want 10 test scores per student Student() /* mem allocated here */ { // Can I do this to init. members? name = "Tommy Trojan"; id = 12313; scores = 10; } }; int main() { Student s1; }

  6. 6 Constructor Initialization Lists Student::Student() : Student:: Student() /* mem allocated here */ name("Tommy"), id(12313), scores(10) { { } name("Tommy Trojan"); id = 12313; scores(10); } You would have to call the member You can't call member constructors in the {…} constructors in the initialization list context • Rather than writing many assignment statements we can use a special initialization list technique for C++ constructors – Constructor(param_list) : member1(param/val), …, memberN(param/val) { … } • We are really calling the respective constructors for each data member

  7. 7 Constructor Initialization Lists Student::Student() : Student::Student() name(), id(), scores() { // calls to default constructors name = "Tommy Trojan"; { id = 12313 name = "Tommy Trojan"; scores.resize(10); id = 12313 } scores.resize(10); } But any member not in the initialization list will You can still assign data members in the {…} have its default constructor invoked before the {…} • You can still assign values (which triggers operator= ) in the constructor but realize that the default constructors will have been called already • So generally if you know what value you want to assign a data member it's good practice to do it in the initialization list to avoid the extra time of the default constructor executing

  8. 8 Constructor Initialization Lists Student::Student() { } Memory is Student::Student(string myname) allocated before string name_ { name_ = myname; the '{' with the id_ = -1; int id_ default constructor } being called… Student::Student(string myname, int myid) { name_ = myname; id_ = myid; …then values } name_ = myname copied in when ... id_ = myid assignment performed using Initialization using operator=() assignment Student::Student() { } name_ = myname Memory is Student::Student(string myname) : allocated and name_(myname), id_(-1) id_ = myid { } filled in "one- Student::Student(string myname, int myid) : step" by calling name_(myname), id_(myid) the copy { } constructor ... Initialization List approach

  9. 9 INHERITANCE

  10. 10 Files for Today • $ mkdir inh • $ cd inh • $ wget http://ee.usc.edu/~redekopp/ee355/code/inh.tar • $ tar xvf inh.tar • $ make – You will get a compile error

  11. 11 Object Oriented Design • Encapsulation – Combine data and operations on that data into a single unit (e.g. a class w/ public and private aspects) • Inheritance – Creating new objects (classes) from existing ones • Polymorphism – Using the same expression to denote different operations

  12. 12 Inheritance • A way of defining interfaces, re-using classes and extending original functionality • Allows a new class to inherit all the data members and member functions from a previously defined class • Works from more general objects to more specific objects – Defines an “is - a” relationship base – Square is-a rectangle is-a shape child – Similar to classification of organisms: grandchild • Animal -> Vertebrate -> Mammals -> Primates

  13. 13 Base and Derived Classes class Person { • Derived classes inherit public: Person(string n, int ident); string get_name(); all data members and int get_id(); private: string name_; int id_; functions of base class }; class Student : public Person { • Student class inherits: public: Student(string n, int ident, int mjr); int get_major(); double get_gpa(); – get_name() and void set_gpa(double new_gpa); private: get_id() int major_; double gpa_; }; – name_ and id_ Class Person Class Student member variables string name_ string name_ int id_ int id_ int major_ double gpa_

  14. 14 Base and Derived Classes class Person { public: Person(string n, int ident); • Derived classes inherit all data string get_name(); int get_id(); members and functions of private: string name_; int id_; base class }; class Student : public Person { • Student class inherits: public: Student(string n, int ident, int mjr); – get_name() and get_id() int get_major(); double get_gpa(); – name_ and id_ member variables void set_gpa(double new_gpa); private: int major_; double gpa_; }; int main() { Class Person Class Student Student s1("Tommy", 1, 9); string name_ string name_ // Student has Person functionality // as if it was written as part of int id_ int id_ // Student cout << s1.get_name() << endl; int major_ double gpa_ }

  15. 15 Inheritance Example Inheritance Diagrams (arrows shown base Component to derived class • Component relationships) – Draw() Window ListBox – onClick() • Window – Minimize() ScrollBox DropDown – Maximize() Box • ListBox – Get_Selection() • ScrollBox – onScroll() • DropDownBox – onDropDown()

  16. 16 Protected Members • Private members of a base class can class Person { public: not be accessed directly by a ... private: derived class member function string name_; int id_; – Code for print_grade_report() would }; not compile since ‘name_’ is private to class Student : public Person { public: class Person void print_grade_report(); • Base class can declare variables private: int major_; double gpa_; with protected storage class }; – Private to anyone not inheriting from void Student::print_grade_report() the base { X cout << “Student “ << name_ << ... – Derived classes can access directly } class Person { public: ... protected: string name_; int id_; };

  17. 17 Constructors and Inheritance • Constructors are only called class Person { public: when a variable ‘enters scope’ Person(string n, int ident); (i.e. is created) and cannot be ... private: called directly string name_; int id_; – How to deal with base }; constructors? class Student : public Person { public: • Also want/need base class or Student(string n, int ident, int mjr); ... other members to be initialized private: before we perform this object's int major_; double gpa_; constructor code }; • Student::Student(string n, int ident, int mjr) Use initializer format instead { – See example below // How to initialize Base class members? Person(n, ident); // No! can’t call Construc. // as a function } Student::Student(string n, int ident, int mjr) : Person(n, ident) { cout << "Constructing student: " << name_ << endl; major_ = mjr; gpa_ = 0.0; }

  18. 18 Constructors & Destructors • Constructors – A Derived class will automatically call its Base class constructor BEFORE it's own constructor executes, either: base • Explicitly calling a specified base class constructor in the child initialization list grandchild • Implicitly calling the default base class constructor if no base class constructor is called in the initialization list Constructor call ordering • Destructors – The derived class will call the Base class destructor automatically AFTER it's own destructor executes • General idea – Constructors get called from base->derived (smaller to base larger) child – Destructors get called from derived->base (larger to grandchild smaller) Destructor call ordering

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend