BEgInSlIdE Copyright 1995 - 2007 C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 1 The C++ Programming Language Object Oriented Programming (inheritance)

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Comp 249 Programming Methodology Chapter 7 - Inheritance – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
BEgInSlIdE OOP-1 Inheritance for Code Reuse uAn Array Example uImproving the Array Example.
Inheritance, Polymorphism, and Virtual Functions
DERIVED CLASSES AND INHERITANCE Moshe Fresko Bar-Ilan University Object Oriented Programing
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
Chapter 12: Adding Functionality to Your Classes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Pointer Data Type and Pointer Variables
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Polymorphism &Virtual Functions
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Object Oriented Programming in C++ Chapter 6 Inheritance.
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Object-Oriented Programming Chapter Chapter
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
Virtual FunctionstMyn1 Virtual Functions A virtual function is declared in a base class by using the keyword virtual. A function that you declare as virtual.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
ISBN Object-Oriented Programming Chapter Chapter
Chapter -6 Polymorphism
Principles of programming languages 10: Object oriented languages Isao Sasano Department of Information Science and Engineering.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Inheritance ndex.html ndex.htmland “Java.
Inheritance and Polymorphism
Object Oriented Programming Elhanan Borenstein Lecture #7.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
7. Inheritance and Polymorphism
Inheritance, Polymorphism, and Virtual Functions
Java Programming Language
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance, Polymorphism, and Virtual Functions
CISC/CMPE320 - Prof. McLeod
Inheritance and Polymorphism
Java Programming Language
Presentation transcript:

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 1 The C++ Programming Language Object Oriented Programming (inheritance) Chapter 9

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 2 Suppose we want to computerize our personnel records... We start by identifying the two main types of employees we have: struct Engineer { Engineer *next; char *name; short year_born; short department; int salary; char *degrees; void give_raise( int how_much ); //... }; struct SalesPerson { SalesPerson *next; char *name; short year_born; short department; int salary; double *comission_rate; void give_raise( int how_much ); //... }; The Personnel Example The magic of M$

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 3 Identifying the Common Part class Employee { char *name; short year_born; short department; int salary; Employee *next; void give_raise( int how_much ); //... }; class Employee { char *name; short year_born; short department; int salary; Employee *next; void give_raise( int how_much ); //... }; class Engineer: Employee { char *degrees; //... }; class Engineer: Employee { char *degrees; //... }; class SalesPerson: Employee { double *commission_rate; //... }; class SalesPerson: Employee { double *commission_rate; //... }; C version: struct Engineer { struct Employee E; char *degree; /*... */ }; C version: struct Engineer { struct Employee E; char *degree; /*... */ }; Indeed, inclusion is a poor man’s (poor) imitation of inheritance!

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 4 oThe Behaviour and the Data associated with a subclass are an extension of the properties of the superclass.  Engineer and SalesPerson extend, each in its own way, the data and behavior of Employee.  Identifying the Employee abstraction, helps us define more types: Inheritance class Manager: Employee { char *degrees; //... }; class Manager: Employee { char *degrees; //... };

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 5 Inheritance Mechanism oA class may inherit from a base class, in which case the inheriting class is called a derived class. oA class may override inherited methods (member functions), but not inherited data. oA Hierarchy of related classes, that share code and data, is created. oInheritance can be viewed as an incremental refinement of a base class by a new derived class. Base class Derived class Arrows are always from a derived class to the base class, since the derived class knows about the base class, but not vice-versa.

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 6 The Benefits of Inheritance 4 Software Reusability. Inheritance allows you to modify or extend a package somebody gave you without touching the package's code Saves programmer time: increase reliability, decrease maintenance cost, and, if code sharing occurs, smaller programs.. 4 Consistency of Interface. An overridden function must have the same parameters and return type: Saves user time: Easier learning, and easier integration. guarantee that interface to similar objects is in fact similar.. 4 Polymorphism. Different objects behave differently as a response to the same message. Least important ! More important ! Most important !

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 7 Inheritance Vector Example Here is a simple version of a Vector class that implements an unchecked array of integers: class Vector { int len, *buff; public: Vector(int l): len(l), buff(new int[l]){} ~Vector() { delete[] buff; } int size() const { return len; } int& operator[](int i) { return buff[i]; } }; class Vector { int len, *buff; public: Vector(int l): len(l), buff(new int[l]){} ~Vector() { delete[] buff; } int size() const { return len; } int& operator[](int i) { return buff[i]; } }; int main() { Vector v(10); // Populate the vector, and then use it. v[5] = v[6] + 5; //.. }

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 8 A Checked Vector oWe may also need a vector whose bounds are checked on every reference.  This is done by defining a new derived class CheckedVector that inherits the characteristics of the base class Vector, and overrides some of its methods: class CheckedVector: public Vector { public: CheckedVector(int size): Vector(size) {} int& operator[](int); // A primitive overriding }; int& CheckedVector :: operator[](int i) { if (0 > i || i >= size()) error(); // Exceptions :-( return Vector::operator[](i); } class CheckedVector: public Vector { public: CheckedVector(int size): Vector(size) {} int& operator[](int); // A primitive overriding }; int& CheckedVector :: operator[](int i) { if (0 > i || i >= size()) error(); // Exceptions :-( return Vector::operator[](i); }

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 9 Points Of Interest  When a class inherits from a class/struct, the public keyword should be used, as in (Don’t ask why at this time.)  Constructors are not Inherited. If we haven’t defined a constructor for CheckedVector, then the compiler would try to generate an empty default constructor and fail in doing so since there is no default constructor of the base class Vector.  The construction (initialization) of the sub-object of the inherited class Vector must be done in the initialization list of the constructor of the derived class CheckedVector class CheckedVector: public Vector {... class CheckedVector: public Vector {... CheckedVector(int size): Vector(size) {}... CheckedVector(int size): Vector(size) {}...

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 10 More Points of Interest  CheckedVector overrides the array reference function of Vector.  Since CheckedVector doesn’t override the size function of Vector, the following calls the inherited function + An overridden function can be called as follows:... return Vector :: operator[] (i); return Vector :: operator[] (i); if (0 > i || i >= size()) if (0 > i || i >= size()) int& CheckedVector :: operator[](int i) int& CheckedVector :: operator[](int i)....

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 11 Data Hiding and Derived Classes  private members of the base class are not accessible to the derived class  Otherwise, privacy is completely compromised by an inherited type.  public members of the base class are accessible to anyone  protected members of the base class are accessible to derived classes only class Vector { protected: int len, *data; public: //... }; class Vector { protected: int len, *data; public: //... }; Protected data members make derived classes addicted Protected data members make derived classes addicted

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 12 Inheritance as Type Extension E = M; // OK M = E; // Error is_manager_of give_raise Manager Employee Employee E; Manager M; This will first call the (compiler generated) type casting operator from Manager to Employee and then call the (compiler-defined or user-defined) Employee to Employee assignment operator. Employee Manager E M

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 13 Is-A Relationship A derived class is a (more specialized) version of the base class: Manager is an Employee CheckedVector is a Vector. LandVehicle is a Vehicle. Thus, any function taking the class B as an argument, will also accept class D derived from B. class Complex {... }; Complex operator +(const Complex& c1, const Complex& c2) {... } class BoundedComplex: public Complex {... } z1, z2; Complex c = z1 + z2; class Complex {... }; Complex operator +(const Complex& c1, const Complex& c2) {... } class BoundedComplex: public Complex {... } z1, z2; Complex c = z1 + z2; The last statement calls operator+(Complex,Complex) using type conversion. Only with public inheritance Only with public inheritance

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 14 Calling Methods of Inherited Types E.give_raise(10); // OK M.give_raise(10); // OK E.is_manager_of(...); // Error M.is_manager_of(E); // OK Employee E; Manager M; Again, Manager is an Employee but not vice-versa! is_manager_of give_raise Manager Employee

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 15 pM = &E; // Error pE = &M; // OK M = *pE // Error M = *(Manager *)pE; // OK … if you know what you are doing M = *static_cast (pE); // MUCH safer Using Pointers to Inherited Types Employee E, *pE; Manager M, *pM; A pointer to an inherited type is generated whenever an inherited method is called. Rules for pointer mixing: is_manager_of give_raise Manager Employee Manager E M pE pM Would compile even if pE were a pointer to int Would compile even if pE were a pointer to int

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 16 Pointer Arrays Employee *Dept[100]; In many cases it is convenient to have a mixed type collections. The simplest and easiest way to do so is to use an array of pointers to the base type (the superclass). It is easy to deposit objects into the above array, however, determining what type of object resides in each location is not so easy (and here starts REAL OOP). is_manager_of give_raise Manager Employee

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 17 give_raise Calling Methods of Inherited Types (revisited) E.give_raise(10); // Employee::give_raise(); M.give_raise(10); // Employee::give_raise(); S.give_raise(10); // SalesPerson::give_raise(); Employee E; Manager M; SalesPerson S; SalesPerson give_raise Employee void SalesPerson::give_raise(int how_much) { Employee::give_raise(how_much + commission_rate * total_sales); } void SalesPerson::give_raise(int how_much) { Employee::give_raise(how_much + commission_rate * total_sales); } Manager

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 18 Employee *Dept[len]; Employee E; Manager M; SalesPerson S; for (i=0; i give_raise(10); give_raise SalesPerson give_raise Employee Manager Since array elements are accessed via Employee* the Employee::give_raise() will be called for all objects Calling Methods of Inherited Types (Cont.)

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 19 Determining the Object Type Given a pointer of type base* (where base is a base class), how do we know the actual type of the object being pointed to ? give_raise SalesPerson give_raise Employee Manager Ensure that only objects of a single type are always pointed to. Place a type field in the base class and update it in the constructor of the derived class. Use virtual functions. There are three solutions:

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 20 Polymorphism Virtual functions give full control over the behavior of an object, even if it is referenced via a base class pointer (or reference). class Employee {... public:... virtual void give_raise(int how_much) {...}; }; class Employee {... public:... virtual void give_raise(int how_much) {...}; }; class SalesPerson: public Employee {... double *commission_rate; public:... virtual void give_raise(int how_much) {...}; }; class SalesPerson: public Employee {... double *commission_rate; public:... virtual void give_raise(int how_much) {...}; }; Never redefine an inherited nonvirutal function Never redefine an inherited nonvirutal function

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 21 V V Polymorphism Employee *Dept[len]; Employee E; Manager M; SalesPerson S; for (i=0; i give_raise(10); give_raise SalesPerson give_raise Employee Manager Although array elements are accessed via Employee* the appropriate ::give_raise() is always called ! Ye t, Dept[i]->is_manager_of(E) is illegal Ye t, *( Dept[i]).is_manager_of(E) is illegal for (i=0; i<len; i++) *(Dept[i]).give_raise(10); Polymorphism works also when using the dereferencing operator

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 22 Polymorphism Sometimes, the type of the object pointed to by a base class pointer is known only at run-time Polymorphism enables dynamic binding (as opposed to static binding). This means that the identity of the virtual function being called is determined at run-time. for (i=0; i<len; i++){ cout << “Enter type of employee (M/S): “; cin >> employee_type; if (employee_type == ‘M’) Dept[i]= new Manager(...); else Dept[i]= new SalesPerson(...); //... for (i=0; i<len; i++){ cout << “Enter type of employee (M/S): “; cin >> employee_type; if (employee_type == ‘M’) Dept[i]= new Manager(...); else Dept[i]= new SalesPerson(...); //...

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 23 Run Time Type Identification (RTTI) Employee *Dept[len]; Employee E; Manager M; SalesPerson S; SalesPerson Employee Manager Suppose we want to call the function is_manager_of only in case the object is of type Manager for (i=0; i<len; i++){ for(j=0; j<len; ++j){ // in case *Dept[i] is the manager // of Dept[j], print something } } for (i=0; i<len; i++){ for(j=0; j<len; ++j){ // in case *Dept[i] is the manager // of Dept[j], print something } }

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 24 Run Time Type Identification (RTTI) The Operator typeid can identify an object’s type at run- time. It can be applied to an object or to a type name. It returns an object of type type_info. The type_info class has the overloaded operator==. for (i=0; i<len; i++){ for(j=0; j<len; ++j){ if (typeid(*Dept[i]) == typeid(Manager)) if(((Manager*)(Dept[i]))-> is_manager_of(Dept[j]) // print something } } for (i=0; i<len; i++){ for(j=0; j<len; ++j){ if (typeid(*Dept[i]) == typeid(Manager)) if(((Manager*)(Dept[i]))-> is_manager_of(Dept[j]) // print something } }

bEgInSlIdE Copyright C. Gotsman & Y.M. Kimchi, Computer Science Dept. Technion 25 Constructors and Destructors Constructors and Destructors cannot be inherited. They always call their base-class counterparts. But while Ctors are never virtual, Dtors may be virtual. Any class that has a virtual function, or even just designed to have derived classes with virtual functions must define a virtual Dtor. class Employee { public: Employee(char *n, int d); virtual ~Employee();... }; class Employee { public: Employee(char *n, int d); virtual ~Employee();... }; class Manager : public Employee { public:... Manager(char *n, int l, int d) : Employee(n,d), level l, group(0){} virtual ~Manager(); }; class Manager : public Employee { public:... Manager(char *n, int l, int d) : Employee(n,d), level l, group(0){} virtual ~Manager(); }; A Ctor that calls a virtual function, cannot call a derived-class’ version of that function.