1 Inheritance We are modeling the operation of a transportation company that uses trains and trucks to transfer goods. A suitable class hierarchy for the.

Slides:



Advertisements
Similar presentations
Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
Advertisements

Chapter 1 OO using C++. Abstract Data Types Before we begin we should know how to accomplish the goal of the program We should know all the input and.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 15: Polymorphism,
Object-Oriented Programming in C++ Lecture 7 Polymorphism.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
Polymorphism, Virtual Methods and Abstract Classes.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
1 Inheritance: constructors Constructors, copy constructors and destructors are NOT inherited. Each subclass has its own constructors and destructor to.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 17 – Payroll Application: Introducing Inheritance.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
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 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
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
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Cpt S 122 – Data Structures Polymorphism
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
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.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
TCP1201 OOPDS Lecture 4 1. Learning Objectives  To understand upcasting & downcasting  To understand static polymorphism and dynamic polymorphism 
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.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Chapter -6 Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Object Oriented Programming Elhanan Borenstein Lecture #7.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
C++ How to Program, 7/e.  There are cases in which it’s useful to define classes from which you never intend to instantiate any objects.  Such classes.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism, Virtual Methods and Abstract Classes
7. Inheritance and Polymorphism
Polymorphism &Virtual Functions
Class A { public : Int x; A()
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Inheritance: hiding methods
Polymorphism & Virtual Functions
Polymorphism Lec
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Polymorphism Polymorphism
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
VIRTUAL FUNCTIONS RITIKA SHARMA.
C++ Polymorphism Reference and pointer implicit type casting
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Computer Science II for Majors
Presentation transcript:

1 Inheritance We are modeling the operation of a transportation company that uses trains and trucks to transfer goods. A suitable class hierarchy for the vehicles is: We will store all the vehicle information in array. Create an array of n vehicle objects. Some will be trains, and the rest will be trucks. How do we do it? Vehicle Truck Train

2 Vehicle hierarchy, take 1 class Vehicle { public: Vehicle() { } void print() { cout << “Vehicle\n”;} }; class Train : public Vehicle { public: Train() { } void print() { cout << “Train\n”;} }; class Truck : public Vehicle { public: Truck() { } void print() { cout << “Truck\n”;} }; int main () { Vehicle *fleet[2]; fleet[0] = new Train; fleet[0]->print(); fleet[1] = new Truck; fleet[1]->print(); delete fleet[0]; delete fleet[1]; return 0; } Output: Vehicle fleet[0] is of type Vehicle!

3 Inheritance & virtual functions A Train is a Vehicle, so the syntax fleet[0] = new Train; works, but ultimately, *fleet[0] is a Vehicle object, so we cannot apply any Train methods to it. We would like our program to have the capability to determine the type of an object (e.g. *fleet[0]) at execution time. There is such a mechanism and it's called RTTI (Run-Time Type Information) We will use virtual functions which allow the program to choose the derived class function, dynamically, instead of the base class function. Vehicle *fleet[2]; fleet[0] = new Train; fleet[1] = new Truck;

4 Vehicle hierarchy, take 2 class Vehicle { public: Vehicle() { } virtual void print() { cout << “Vehicle\n”; } }; class Train : public Vehicle { public: Train() { } virtual void print() { cout << “Train\n”; } }; class Truck : public Vehicle { public: Truck() { } virtual void print() { cout << “Truck\n”; } }; int main () { Vehicle *fleet[2]; int vehicle_type; for (int i=0; i<2; i++) { cout << "Enter 1 for Train,2 for Truck"; cin >> vehicle_type; if (vehicle_type == 1) fleet[i] = new Train; else fleet[i] = new Truck; fleet[0]->print(); fleet[1]->print(); delete fleet[0]; delete fleet[1]; return 0; } The appropriate method is called based on the dynamic type of fleet[i]. The dynamic types of *fleet[0] and *fleet[1] are determined at runtime. For input 1 2 the output is: Train Truck

5 Virtual functions If a class has virtual methods, then the destructor must also be virtual! class Vehicle { public: Vehicle() { } ~Vehicle { } virtual void print() {}; }; class Train : public Vehicle { public: Train() { } ~Train { } virtual void print() {}; } ; int main () { Vehicle *t = new Train; delete t; return 0; } The sequence of constructor/destructor calls in this program is: Vehicle() Train() ~Vehicle() The Train destructor was never called, because it's not virtual! The Vehicle destructor was called because this is the type of *t.

6 Virtual functions If a class has virtual methods, then the destructor must also be virtual! class Vehicle { public: Vehicle() { } virtual ~Vehicle { } virtual void print() {}; }; class Train : public Vehicle { public: Train() { } virtual ~Train { } virtual void print() {}; } ; int main () { Vehicle *t = new Train; delete t; return 0; } Now, the sequence of constructor/destructor calls is correct: Vehicle() Train() ~Train() ~Vehicle()

7 Assignments der = b; // ERROR! A Base object is not always a Derived object. // Note: what values will be given to the "extra" data // members of the Derived object? pder = pb // ERROR! Same reason as above. class Base {... }; class Derived : public Base {...}; Base b, *pb; Derived der, *pder;

8 Assignments b = der; // OK! A Derived object is also a Base object pb = pder; // Mostly OK! pb->basefunc() will work (basefunc() is a Base member function) pb->derivedfunc() will give a compiler ERROR (derivedfunc() is a Derived member function) class Base {... }; class Derived : public Base {...}; Base b, *pb; Derived der, *pder;

9 Assignments pb = new Derived; pder = pb ; // ERROR! pb = new Derived; pder = (Derived*) pb ; // Dangerous! We are trying to downcast! However, there is a case when we may have to downcast. class Base {... }; class Derived : public Base {...}; Base b, *pb; Derived der, *pder;

10 Downcasting We'd like to do this: int main () { Vehicle *fleet[2]; int vehicle_type; for (int i=0; i<2; i++) { cout << "Enter 1 for Train,2 for Truck"; cin >> vehicle_type; if (vehicle_type == 1) fleet[0] = new Train; else fleet[1] = new Truck; for (int i=0; i<2; i++) { if *fleet[i] is a train, do A else, do B }... How can we check the dynamic type of *fleet[i] at runtime? Trick: Create a Train pointer and assign fleet[i] to it. Use the dynamic_cast method to perform this downcasting (from Vehicle* to Train*) If fleet[i]'s dynamic type is also Train*, then the casting will succeed. If it's not (i.e. it's a Truck* instead), then the casting fails, and the pointer is NULL.

11 Downcasting int main () { Vehicle *fleet[2]; int vehicle_type; for (int i=0; i<2; i++) { cout << "Enter 1 for Train,2 for Truck"; cin >> vehicle_type; if (vehicle_type == 1) fleet[0] = new Train; else fleet[1] = new Truck; for (int i=0; i<2; i++) { Train *tr = dynamic_cast ( fleet[i] ); if (tr != NULL) // it means that fleet[i] was indeed a train // do A, else // do B....

12 Multiple inheritance A class may inherit from more than one base class. JetCar inherits the members of Car and those of Jet. JetCar's constructor calls the constructors of Car and Jetin the order specified in JetCar's definition (i.e. as they appear after the colon) class Car {... }; class Jet {... }; class JetCar: public Car, public Jet{... };

13 Multiple inheritance What if we have: JetCar's constructor calls the constructor of Car which calls the constructor of Vehicle and then calls the constructor of Jet which calls the constructor of Vehicle The Vehicle constructor was called twice! class Vehicle {... }; class Car : public Vehicle {... }; class Jet : public Vehicle {... }; class JetCar: public Car, public Jet {... };

14 Multiple inheritance Use virtual inheritance to tell the compiler that the base class constructor should be called only once: JetCar's constructor calls the constructor of Car which calls the constructor of Vehicle and then calls the constructor of Jet class Vehicle {... }; class Car : virtual public Vehicle {... }; class Jet : virtual public Vehicle {... }; class JetCar: public Car, public Jet {... };

15 Abstract classes Since the company has either trucks or trains, we would like to disallow the creation of Vehicle objects. We want to force the compiler to give an error in the following case: In other words, we want to make Vehicle an abstract class. This will make Train and Truck concrete classes. To make a class as abstract, we declare one of its virtual methods to be "pure", by placing a =0 at the end of its declaration. Vehicle *v; v = new Vehicle; // ERROR: We should only create // a train or a truck!

16 Abstract classes Pure virtual functions typically do not have an implementation. Every concrete derived class MUST override all base class pure virtual functions. Even though we can't instantiate abstract class objects, we can still use the abstract class to create pointers. Vehicle *v; // OK Vehicle *v = new Train; // OK Vehcile *v = new Vehicle // ERROR! class Vehicle { public: Vehicle() { } virtual void print() = 0; }; class Train : public Vehicle { public: Train() { } void print() { cout << “Train\n”;} }; class Truck : public Vehicle { public: Truck() { } void print() { cout << “Truck\n”;} };