Chapter 4 Inheritance.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
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.
C++ Inheritance Gordon College CPS212. Basics OO-programming can be defined as a combination of Abstract Data Types (ADTs) with Inheritance and Dynamic.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Inheritance, Polymorphism, and Virtual Functions
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
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 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
Pointer Data Type and Pointer Variables
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Chapter 11: Inheritance and Composition. Objectives In this chapter, you will: – Learn about inheritance – Learn about derived and base classes – Redefine.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
OOP, Virtual Functions and Inheritance
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.
Inheritance. Lecture contents Inheritance Class hierarchy Types of Inheritance Derived and Base classes derived class constructors protected access identifier.
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.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter 11: Inheritance and Composition. Introduction Two common ways to relate two classes in a meaningful way are: – Inheritance (“is-a” relationship)
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
Computer Science Department Inheritance & Polymorphism.
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.
A First Book of C++ Chapter 12 Extending Your Classes.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Polymorphism &Virtual Functions
Object-Oriented Programming
Inheritance and Run time Polymorphism
Chapter 5 Classes.
Inheritance & Polymorphism
Polymorphism & Virtual Functions
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
3.3 Abstract Classes, Assignment, and Casting in a Hierarchy
Virtual Functions Department of CSE, BUET Chapter 10.
Programming II Polymorphism A.AlOsaimi.
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Chapter 11: Inheritance and Composition
Overview of C++ Polymorphism
VIRTUAL FUNCTIONS RITIKA SHARMA.
Computer Science II for Majors
Presentation transcript:

Chapter 4 Inheritance

Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism Public, private, and protected members and inheritance Static vs. dynamic binding Default constructor, copy constructor, and copy assignment operator Abstract classes Tricky C++ stuff

4.1 What is Inheritance? Another mechanism for code reuse. A process of deriving classes from a base class without disturbing the implementation of the base class. Inheritance models the IS-A relationship. In a is-a relationship the derived class is a variation of the base class. Ex: Vehicle is a class Car is a Vehicle => Car derived from Vehicle

Inheritance Concept A key feature of C++ classes is inheritance. Inheritance allows to create classes which are derived from other classes, so that they automatically include some of its "parent's" members, plus its own. For example, we are going to suppose that we want to declare a series of classes that describe polygons like our CRectangle, or like CTriangle. They have certain common properties, such as both can be described by means of only two sides: height and base. This could be represented in the world of classes with a class CPolygon from which we would derive the two other ones: CRectangle and CTriangle.

Inheritance Concept Polygon Rectangle Triangle class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Polygon Rectangle Triangle class Polygon{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area();}; Ref: http://www.cse.ohio-state.edu/~neelam/courses/45922/

Inheritance Concept Polygon Rectangle Triangle class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; Polygon Rectangle Triangle class Rectangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area();}; class Rectangle : public Polygon{ public: float area(); };

Inheritance Concept Polygon Rectangle Triangle class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; Polygon Rectangle Triangle class Triangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area();}; class Triangle : public Polygon{ public: float area(); };

Figure 4.2 istringstream istream fstream ifstream IOS iostream ostringstream ofstream

4.2 Inheritance Basics Public inheritance: all public members of the base class remain public in the derived class =>models is-a relationship =>mostly used. Private inheritance: hidden all inherited members from the public => models has-a relationship. Syntax: class DerivedClassName : access-level BaseClassName

General layout of public inheritance class Derived: public Base{ // any members that are not listed are inherited unchanged //except for constructor, destructor, copy constructor, and //operator = public: //constructors, and destructors if defaults are not good // Base members whose definitions are to change in Derived // Additional public member functions private: //Additional data members(generally private) // Additional private member functions // Base members that should be disabled in Derived };

Inheritance Derived class inherits all member functions from the base class. It may accept, disallow, or redefine them. Derived class can define new functions. Derived class can access public and protected members of the base class.

Access Rules Public Inheritance Situation Public Protected Private Base class member function accessing M Yes Derived class member function accessing M No Main, accessing B.M Main, accessing D.M Derived class member function accessing B.M Note: B is an object of the base class; D is an object of the publicly derived class; M is member of the base class.

Constructor and Base class initialization Constructors should be defined for each derived class. If there is no constructor in a derived class, a default zero-parameter constructor will be generated which in turn calls the zero-parameter constructor in the base class to initialize the inherited members Derived() : Base() { }

Overriding a method (member function) Overriding base class methods: Derived class methods must have the same signature and compatible return types with the base class methods. Partial overriding: overriding base class methods by adding more functionality.

Example of partial method overriding class Workaholic : public Worker { public: void doWork(){ // overriding base method Worker::doWork();// call base method drinkCoffee(); // new method Worker::doWork(); // call base method } };

Bindings Static binding: the decision about which function/type to use to resolve an overload is made at compile time. Dynamic binding: the decision must be made at run time. If a function is redefined in a derived class, it should be declared virtual in the base class. Example: class Worker{ public: virtual void doWork(); };

Examples Worker *wptr; Worker w; cin>>x; Workaholic wh; if(x != 0) wptr = new Workaholic(); else wptr = new Worker(); . . . //which doWork is used ? wptr -> doWork(); Figure 4.9 dynamic binding Worker w; Workaholic wh; . . . w.doWork(); wh.doWork(); figure 4.8 static binding

Polymorphism Static and dynamic binding In most programming languages and in most cases the variables are bound to a specific type at compile time Static binding Dynamic binding The type of the variable can change at run time Using pointers to classes related by inheritance in C++ In C we can use unions to allow dynamic binding of arbitrary types Dangerous in some cases Ref: www.cs.uh.edu/~mirkovic/cosc1305/

Polymorphism Polymorphism, many forms, using the same name for “many different things.” Polymorphism is the ability of a reference variable to reference objects of several different types. When operations are applied to the variable, the operation that is appropriate to the actual reference object is automatically selected. Derived class is a new class which inherits all public & protected properties of a base class. Derived class is type-compatible with its base class.

C++ Polymorphism Definition: Single name denotes objects of different classes related by inheritance Ability to manipulate derived objects using the interface defined in the base class Example: class Employee { public: void CalcPay (); }; class SalariedEmployee :public Employee{

Example Which function is called? Employee *ep; ep = new SalariedEmployee; Ep->CalcPay(); Which function is called? The function in Employee is called To avoid that we have to declare CalcPay() as a virtual function

Virtual Functions Definition: Example: Nonstatic member function prefaced by the virtual specifier. Compiler generates the code that will select the appropriate function at runtime Example: class Employee { public: virtual void CalcPay (); }; class SalariedEmployee :public Employee{ virtual specifier needs to appear in the base class only.

Examples Employee *p0 = new Employee; Employee *p1 = new SalariedEmployee; p0->CalcPay(); // calls Employee::CalcPay() p1->CalcPay(); // calls SalariedEmployee::CalcPay() Any nonstatic member function except a constructor can be virtual Virtual functions can also be friends of other classes Some compilers require the class destructor to be virtual if a class contains any virtual functions

C++ Virtual Function   C++ virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. The whole function body can be replaced with a new set of implementation in the derived class.

Properties of Virtual Functions The main difference between a non-virtual C++ member function and a virtual member function is in the way they are both resolved. A non-virtual C++ member function is resolved during compile time or static binding. Virtual Functions are resolved during run-time or dynamic binding Virtual functions are member functions of a class. Virtual functions are declared with the keyword virtual. Virtual function takes a different functionality in the derived class.

v - table Whenever a program has a virtual function declared, a v-table is constructed for the class. The v-table consists of addresses to the virtual functions for classes that contain one or more virtual functions.

Virtual A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor. Destructors should be virtual for base class => Let the computer know which one to call for deallocation.

virtual destructor A virtual destructor is one that is declared as virtual in the base class and is used to ensure that destructors are called in the proper order. It is to be remembered that destructors are called in the reverse order of inheritance. If a base class pointer points to a derived class object and we some time later use the delete operator to delete the object, then the derived class destructor is not called.

In this case the type of the pointer would be considered. #include <iostream.h> class base {    public:    ~base()   {   } }; class derived : public base {    public:    ~derived()    {      } }; void main() {    base *ptr = new derived();    // some code    delete ptr; } In this case the type of the pointer would be considered. Hence as the pointer is of type base, the base class destructor would be called but the derived class destructor would not be called at all. The result is memory leak. In order to avoid this, we have to make the destructor virtual in the base class.

#include <iostream #include <iostream.h> class base { public: virtual ~base() { } }; class derived : public base {    public:    ~derived()    {    } }; void main() {    base *ptr = new derived();    // some code    delete ptr; } no memory leak here.

General rules Nonvirtual functions: Overloading is resolved at compile time. Virtual functions: Overloading is resolved at run-time Pure virtual functions Overloading is resolved at run-time.

Abstract Abstract method: A pure virtual function, has no meaningful definition in the base class and must always be defined in derived classes. Abstract class: a class containing any abstract method = > can NOT be instantiated and must be inherited. Example: shape class

Figure 4.13 The abstract base class shape public: Shape( const string & shapeName = "" ) : name( shapeName ) { } virtual ~Shape( ) { } virtual double area( ) const = 0; //abstract method bool operator< ( const Shape & rhs ) const { return area( ) < rhs.area( ); } virtual void print( ostream & out = cout const { out << name << " of area "<< area( ); } private: string name; };

4.3 Examples: Expanding the Shape class Provide new constructors Write definition for inherited pure virtual functions. Shape.cpp Example: Shape *a, *b; a= new Circle (3, 0) //legal b= new Shape (“circle”) //illegal

4.4 Tricky C++ Details Changing the default value in a derived class is unsafe because doing so can create an inconsistency with virtual functions. When a method is declared in a derived class, it hides all methods of the same name in the base class => get away by partial overriding or using “using” directive

class Base{ public: virtual void bar(); }; class Derived{ void bar(int x); Void test( Base & arg1, Derived & arg2){ arg1.bar(); // call Base::bar() => OK arg1.bar(4); //call Base::bar(int) => fails for not existing => OK arg2.bar(4); // call Derived::bar(int) => OK arg2.bar(); // fails b/c Derived::bar(int) has hidden Base::bar() } Get away by define one of the following two void bar(){Base::bar();} // in Derived class using Base::bar; // new std, may not be accepted by some compilers

Inheritance Cont . . An inherited method can be overridden required that the new method must have exact signature and the return type must be the same or of a derived type from the base class. Default inheritance is private. Try to avoid it. Friend functions of a base class are not friends of the derived ones. Slicing: casting a derived class to its base will surrender data defined in the derived class.

//: C15:Slice.cpp // Object slicing #include <iostream> using namespace std; class Base { int i; public: Base(int ii = 0) : i(ii) {} virtual int sum() const { return i; } }; class Derived : public Base { int j; public: Derived(int ii = 0, int jj = 0) : Base(ii), j(jj) {} int sum() const { return Base::sum() + j; } }; void call(Base b) { cout << "sum = " << b.sum() << endl; } int main() { Base b(10); Derived d(10, 47); call(b); call(d); } ///:~

Slicing The function call( ) is passed an object of type Base by value . It then calls the virtual function sum( ) for the Base object. Two things are happening in this program. First, call( ) accepts only a Base object, so all the code inside the function body will manipulate only members associated with Base. Any calls to call( ) will cause an object the size of Base to be pushed on the stack and cleaned up after the call. This means that if an object of a class inherited from Base is passed to call( ), the compiler accepts it, but it copies only the Base portion of the object. It slices the derived portion off of the object, like this:

4.5 Multiple Inheritance A mechanism for deriving a class from several base classes. Ex: Student and Employee are derived classes of UniversityPerson. class Student: virtual public UniversityPerson(){. . . }; class Employee:virtual public UniversityPerson(){…}; class StudentEmployee : public Student, public Employee{. . .}; Virtual inheritance prevents duplicate data members inherited from base classes.

What a derived class inherits Every data member defined in the parent class (although such members may not always be accessible in the derived class!) Every ordinary member function of the parent class (although such members may not always be accessible in the derived class!) The same initial data layout as the base class What a derived class doesn't inherit The base class's constructors and destructor The base class's assignment operator The base class's friends

What happens when a derived-class object is created and destroyed 1. Space is allocated (on the stack or the heap) for the full object (that is, enough space to store the data members¤¤ inherited from the base class plus the data members defined in the derived class itself) 2. The base class's constructor is called to initialize the data members inherited from the base class 3. The derived class's constructor is then called to initialize the data members¤¤ added in the derived class 4. The derived-class object is then usable 5. When the object is destroyed (goes out of scope or is deleted) the derived class's destructor is called on the object first 6. Then the base class's destructor¤ is called on the object 7. Finally the allocated space for the full object is reclaimed http://burks.bton.ac.uk/burks/language/cpp/cppfaq/privatei.htm

Common errors (page 151) Inheritance is private by default. A common error is to omit the keyword public, which is needed to specify public inheritance. Objects of abstract classes can NEVER be initiated. More errors defined in page 151

Three Types of Inheritance Access level of members will be changed by derivation. (private parts will always be invisible in derived class.) “public” inheritance Base Derived private (invisible) protected protected public public “private” inheritance protected private public private “protected” inheritance public protected protected, public parts will be unchanged (struct’s default) protected, public parts will be private (class’s default) protected, public parts will be protected

In class exercises When should a constructor be virtual? When should a destructor be virtual? Explain the rules when to use virtual and non-virtual functions.

Summary Inheritance: a powerful way for code reuse Virtual: Dynamic binding, binding at execution time. Abstract: must be defined in derived classes. Abstract classes can’t be instantiated. Friendship is not inheritable.

Homework Hw 2: 3.4, 4.5, due on next wed. Finish reading chapter 4 and preview chapter 6