CSCI 104 Inheritance. Mark Redekopp David Kempe

Similar documents
CSCI 104 Inheritance. Mark Redekopp David Kempe

CSCI 104 Polymorphism. Mark Redekopp David Kempe

CS 103 Unit 10 Slides

CS 103 Unit 10 Slides

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

CMSC 132: Object-Oriented Programming II. Inheritance

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

EE 355 Unit 13 C++ STL; Iterators, Maps, Sets. Mark Redekopp

CSCI 104 C++ STL; Iterators, Maps, Sets. Mark Redekopp David Kempe

CSCI 104 Searching and Sorted Lists. Mark Redekopp David Kempe

CSCI 104. Rafael Ferreira da Silva. Slides adapted from: Mark Redekopp and David Kempe

CS 520 Theory and Practice of Software Engineering Fall 2017

CSCI 104 Exceptions. Mark Redekopp David Kempe

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CSC1322 Object-Oriented Programming Concepts

CSCI 104 Templates. Mark Redekopp David Kempe

Inheritance and Polymorphism

Data Structures and Other Objects Using C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Abstract Data Types

Darrell Bethea June 6, 2011

COSC 320 Exam 2 Key Spring Part 1: Hash Functions

Multiple Inheritance and Object Layout in C++

CS 320 Introduction to Software Engineering Spring March 06, 2017

CSCI 104 Templates. Mark Redekopp David Kempe

Inheritance, and Polymorphism.

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Lecture 11. Demonstration #1. More Inheritance, More Constructors. Absolute C++ Chapter 15. Virtual Functions. Overriding

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Week 5-1: ADT Design

CSCI 104 Searching and Sorted Lists. Mark Redekopp David Kempe Sandra Batista

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

CS 103 Unit 11. Linked Lists. Mark Redekopp

VI. INHERITANCE AND DERIVED CLASSES

A First Object. We still have another problem. How can we actually make use of the class s data?

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

System Design and Programming II

Polymorphism Part 1 1

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Recap: Pointers. int* int& *p &i &*&* ** * * * * IFMP 18, M. Schwerhoff

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

CSCI 101L - Data Structures. Practice problems for Final Exam. Instructor: Prof Tejada

Topic 10: Introduction to OO analysis and design

Programming in C# Inheritance and Polymorphism

CIS 110: Introduction to computer programming

CS105 C++ Lecture 7. More on Classes, Inheritance

Data Structure (CS301)

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

C++ Mini Lessons Last Update: Feb 7, 2018

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Week 11: Class Design

Data Structures (INE2011)

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

CS 162, Lecture 25: Exam II Review. 30 May 2018

CSCI-1200 Data Structures Fall 2016 Lecture 17 Associative Containers (Maps), Part 2

CS Lecture #6. Administrative... Assignment #2 Graded NN Turned In, Average Grade: XX Assignment #3 due on Thursday

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Largest Online Community of VU Students

Object Oriented Software Design II

Inheritance CSC9Y4. Inheritance

Page 1 of 5. *** person.cpp *** #include "person.h" #include <string> #include <iostream> using namespace std; *** person.h ***

Object Oriented Programming

Homework 6. Reading. Problems. Handout 7 CS242: Autumn November

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Object Oriented Software Design II

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

CS 520 Theory and Practice of Software Engineering Fall 2018

Classes in C++98 and C++11

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Object Oriented Programming: Inheritance Polymorphism

Comp151. Inheritance: Introduction

a data type is Types

CS250 Final Review Questions

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

COMP 2355 Introduction to Systems Programming

A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class.

CS 103 Unit 11. Linked Lists. Mark Redekopp

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

Short Notes of CS201

Introduction to Programming Using Java (98-388)

Comp151. Inheritance: Initialization & Substitution Principle

1 Short Answer (7 Points Each)

EE219 - Semester /2009 Solutions Page 1 of 10

A A B U n i v e r s i t y

CS201 - Introduction to Programming Glossary By

C++ (Non for C Programmer) (BT307) 40 Hours

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

Object-Oriented Programming, Iouliia Skliarova

Midterm Review. PIC 10B Spring 2018

INHERITANCE - Part 1. CSC 330 OO Software Design 1

Principles of Object Oriented Programming. Lecture 4

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2015 EOM, HYEONSANG ALL RIGHTS RESERVED

DATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD

COP 3530 Discussion Session #2 Ferhat Ay

Transcription:

CSCI 104 Inheritance Mark Redekopp David Kempe

Files for Today $ mkdir inh $ cd inh $ wget http://ee.usc.edu/~redekopp/cs104/inh.tar $ tar xvf inh.tar $ g++ -g -o inhtest inhtest.cpp student.cpp person.cpp 2

Constructor Initialization Lists class Person Person(); Person(string myname); Person(string myname, int myid); string get_name() return name; void add_grade(int score); int get_grade(int index); string name_; int id_; vector<int> grades_; Person::Person() Person::Person(string myname) name_ = myname; id_ = -1; Person::Person(string myname, int myid) name_ = myname; id_ = myid; string name_ int id_ C++ constructors often have a bunch of assignments and initializations to the data members. 3

Constructor Initialization Lists Person::Person() Person::Person(string myname) name_ = myname; id_ = -1; Person::Person(string myname, int myid) name_ = myname; id_ = myid; Person::Person() Person::Person(string myname) : name_(myname), id_(-1) Person::Person(string myname, int myid) : name_(myname), id_(myid) Initialization using assignment Initialization List approach Rather than writing many assignment statements we can use a special initialization list technique for C++ constructors Constructor(param_list) : member_var1(param1),, member_varn(paramn) This technique may seem superfluous but is helpful/needed when we understand copy semantics and add in the concept of inheritance 4

Constructor Initialization Lists Person::Person() Person::Person(string myname) name_ = myname; id_ = -1; Person::Person(string myname, int myid) name_ = myname; id_ = myid; String Operator=() Called Initialization using assignment Person::Person() Person::Person(string myname) : name_(myname), id_(-1) Person::Person(string myname, int myid) : name_(myname), id_(myid) string name_ int id_ name_ = myname id_ = myid name_ = myname id_ = myid Memory is allocated before the '' then values copied in when assignment performed Memory is allocated and filled in "onestep" String Copy Constructor Called Initialization List approach 5

INHERITANCE 6

Encapsulation Object Oriented Design 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 7

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 Square is-a rectangle is-a shape Square inherits from Rectangle which inherits from Shape Similar to classification of organisms: Animal -> Vertebrate -> Mammals -> Primates base child grandchild 8

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

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

Inheritance Example Component Draw() onclick() Window Minimize() Maximize() ListBox Get_Selection() ScrollBox onscroll() DropDownBox ondropdown() ScrollBox Window Component ListBox Inheritance Diagrams (arrows shown base to derived class relationships) DropDown Box 11

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

Base and Derived Classes Derived class see's base class members based on the base classes specification If Base class said it was public or protected, the derived class can access it directly If Base class said it was private, the derived class cannot access it directly public/private identifier before base class indicates HOW the public base class members are viewed by clients (those outside) of the derived class public => public base class members are public to clients (others can access) private => public base class members are private to clients (not accessible to the outside world) class Person Person(string n, int ident); string get_name(); int get_id(); string name_; int id_; Base Class class Student : public Person Student(string n, int ident, int mjr); int get_major(); double get_gpa(); void set_gpa(double new_gpa); int major_; double gpa_; class Faculty : public Person Faculty(string n, int ident, bool tnr); bool get_tenure(); bool tenure_; Derived Classes 13

Inheritance Access Summary Base class Declare as protected if you want to allow a member to be directly accessed/modified by derived classes Derive as public if You want users of your derived class to be able to call base class functions/methods Derive as private if You only want your internal workings to call base class functions/methods Inherited Base Public Protected Private Public Public Protected Private Protected Protected Protected Private Private Private Private Private External client access to Base class members is always the more restrictive of either the base declaration or inheritance level class Person Person(string n, int ident); string get_name(); int get_id(); string name_; int id_; Base Class class Student : public Person Student(string n, int ident, int mjr); int get_major(); double get_gpa(); void set_gpa(double new_gpa); int major_; double gpa_; class Faculty : public Person Faculty(string n, int ident, bool tnr); bool get_tenure(); bool tenure_; Derived Classes 14

When to Inherit Privately Suppose I want to create a FIFO (First-in, First-Out) data structure where you can only Push in the back Pop from the front FIFO is-a special List Do I want to inherit publicly from List NO!!! Because now the outside user can call the base List functions and break my FIFO order Inherit privately to hide the base class public function and make users go through the derived class' interface class List List(); void insert(int loc, const int& val); int size(); int& get(int loc); void pop(int loc;) IntItem* _head; Base Class class FIFO : public List // or private List FIFO(); push_back(const int& val) insert(size(), val); int& front(); return get(0); void pop_front(); pop(0); Derived Class FIFO f1; f1.push_back(7); f1.push_back(8); f1.insert(0,9) 15

Constructors and Inheritance How do we initialize base class data members? Can't assign base class members if they are private class Person Person(string n, int ident); string name_; int id_; class Student : public Person Student(string n, int ident, int mjr); int major_; double gpa_; Student::Student(string n, int ident, int mjr) name_ = n; // can't access name_ in Student id_ = ident; major_ = mjr; 16

Constructors and Inheritance Constructors are only called when a variable enters scope (i.e. is created) and cannot be called directly How to deal with base constructors? Also want/need base class or other members to be initialized before we perform this object's constructor code Use initializer format instead See example below class Person Person(string n, int ident); string name_; int id_; class Student : public Person Student(string n, int ident, int mjr); int major_; double gpa_; Student::Student(string n, int ident, int mjr) // 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; 17

Overloading Base Functions A derived class may want to redefined the behavior of a member function of the base class A base member function can be overloaded in the derived class When derived objects call that function the derived version will be executed When a base objects call that function the base version will be executed class Car double compute_mpg(); string make; string model; double Car::compute_mpg() if(speed > 55) return 30.0; else return 20.0; class Hybrid : public Car void drive_w_battery(); double compute_mpg(); string batterytype; Class Car string make string model Class Hybrid string make string model string battery double Hybrid::compute_mpg() if(speed <= 15) return 45; // hybrid mode else if(speed > 55) return 30.0; else return 20.0; 18

Scoping Base Functions We can still call the base function version by using the scope operator (::) base_class_name::function_name() class Car double compute_mpg(); string make; string model; class Hybrid : public Car double compute_mpg(); string batterytype; double Car::compute_mpg() if(speed > 55) return 30.0; else return 20.0; double Hybrid::compute_mpg() if(speed <= 15) return 45; // hybrid mode else return Car::compute_mpg(); 19

Inheritance vs. Composition Software engineers debate about using inheritance (is-a) vs. composition (has-a) Rather than a Hybrid is-a Car we might say Hybrid has-a car in it, plus other stuff Better example when we get to Lists, Queues and Stacks While it might not make complete sense verbally, we could re-factor our code the following ways Interesting article I d recommend you read at least once: http://berniesumption.com/software/in heritance-is-evil-and-must-bedestroyed/ class Car double compute_mpg(); string make; string model; double Car::compute_mpg() if(speed > 55) return 30.0; else return 20.0; class Hybrid double compute_mpg(); Car c_; // has-a relationship string batterytype; Class Car string make string model Class Hybrid string _c.make string _c.model string battery double Hybrid::compute_mpg() if(speed <= 15) return 45; // hybrid mode else return c_.compute_mpg(); 20

Another Composition We can create a FIFO that "has" a List as the underlying structure class List List(); void insert(int loc, const int& val); int size(); int& get(int loc); void pop(int loc;) IntItem* _head; Base Class class FIFO List mylist; FIFO(); push_back(const int& val) mylist.insert(size(), val); int& front(); return mylist.get(0); void pop_front(); mylist.pop(0); int size() // need to create wrapper return mylist.size(); FIFO via Composition 21