Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Constructors: Access Considerations DerivedClass::DerivedClass( int iR, float fVar) : BaseClass(fVar) { m_uiRating = uiR; } Alternatively DerivedClass::DerivedClass(
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
Reusing Code Private or Protected inheritance. A cool class for array valarray class deals with numeric values, and it supports operation such as summing.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Inheritance, Polymorphism, and Virtual Functions
Static Class Member Function We can declare a member function being static. A static member function doesn’t have to be invoked by an object. A static.
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 12: Adding Functionality to Your Classes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
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.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
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
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.
 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.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
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.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance.
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.
Effective C++, 2nd Ed. By Scott Myers. Constructors, Destructors, and Assignment Operators 11.Define a copy constructor and an assignment operator for.
Chapter -6 Polymorphism
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Inheritance and Composition Reusing the code and functionality Unit - 04.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Classes: Defining Your Own Data Types Basic principles in OOP Define a new data type as a class and use objects of a class Member Functions –Constructors.
Computer Science Department Inheritance & Polymorphism.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
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.
CMSC 202 Polymorphism.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Programming with ANSI C ++
Polymorphism &Virtual Functions
Class A { public : Int x; A()
Inheritance, Polymorphism, and Virtual Functions
Polymorphism & Virtual Functions
This pointer, Dynamic memory allocation, Constructors and Destructor
Polymorphism Lec
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance, Polymorphism, and Virtual Functions
Chapter 8: Class Relationships
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
VIRTUAL FUNCTIONS RITIKA SHARMA.
C++ Polymorphism Reference and pointer implicit type casting
Presentation transcript:

Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting and downcasting Virtual member functions Early binding and late binding Abstract base classes Pure virtual function Public inheritance

Inheriting classes Base class Derived class Program tabtenn0.h, tabtenn0.cpp, usett0.cpp

Inheritance

Derived class class RatedPlayer : public TableTennisPlayer { private: int rating; public: … };

Base and derived classes

Access specify without inheritance

Initializer list RatedPlayer::RatedPlayer(unsigned int r, const char *fn, const char*ln, bool ht): TableTennisPlayer(fn, ln, ht) { rating = r; } … RatedPlayer rplayer1(1140, “Mallory”, “Duck”, true);

Initializer list RatedPlayer::RatedPlayer(unsigned int r, const char *fn, const char*ln, bool ht): TableTennisPlayer(fn, ln, ht), rating(r) {} … RatedPlayer rplayer1(1140, “Mallory”, “Duck”, true);

Constructor for derived class The base-class object is constructed first The derived-class constructor should pass base-class information to a base-class constructor via a member initializer list The derived-class constructor shoud initialize the data members that were added to the derived class

Using a derived class Program tabtenn1.h, tabtenn1.cpp, usett1.cpp

Access specify with inheritance

Special relationship between base and derived class Derived class uses base class methods Upward casting is allowed Downward casting is not safe

Implicit upward casting void Show(const TableTennisPlayer &rt) { cout << “Name: ”; rt.Name(); cout << “\nTable: ”; if (rt.HasTable()) cout << “yes\n”; else cout << “no\n”; } TableTennisPlayer player1(“Tara”, “Boomdea”, false); RatedPlayer rplayer1(1140, “Mallory”, “Duck”, true); Show(player1); Show(rplayer1);

Implicit copy constructor RatedPlayer olaf1(1190, “Olaf”, “Loaf”, true); TableTennisPlayer olaf2(olaf1), olaf3; // invoke implicit copy constructor and upward casting // TableTennisPlayer(const TableTennisPlayer&); TableTennisPlayer winer = olaf1; TableTennisPlayer winer = TableTennisPlayer(olaf1); olaf3 = olaf1;//assignment op and upward casting

Is-a & has-a relationships

Inheritance model Public –An is-a relationship –Illegal relationships Is-like-a, has-a, is-implemented-as, uses-a Private Protected

Polymorphic public inheritance Redefining base-class methods in a derived class Using virtual methods Program brass.h, brass.cpp, usebrass1.cpp Virtual method behavior and the need for virtual destructors in base class Program usebrass2.cpp

Bindings Static binding (early binding) during compiling Dynamic binding (late binding) during execution

Pointer and reference type compatibility double x = 2.5; int *pi = &x;// invalid, mismatch pointer type long & r = x;// invalid, mismatch reference type BrassPlus dilly(“Annie Dill”, 34854, 3000); Brass *pd = &dilly;// ok Brass &rd = dilly;// ok

Upcasting & downcasting Upcasting –Converting a derived-class reference or pointer to a base-class reference or pointer –Implicit type cast is allowed –Is–a relationship Downcasting –Converting a base-class pointer or reference to a derived-class pointer or reference –Only allow explicit type cast

Upcasting downcasting

Virtual member functions and dynamic binding Virtual function uses dynamic binding, whereas, non-virtual function employs static binding

Virtual or non-virtual? Virtual function –Base class member function is allowed to be redefined in derived class Non-virtual function –Base class member function is not allowed to be redefined in derived class

Why two kinds of binding? Why static is the default? Two reasons –Efficiency – static binding is a little efficient than dynamic binding –The conceptual model – if you don’t want to redefine member functions in derived classes

How virtual function work? Virtual function table (vtbl) Scientist sophie(“Sophie Fant”);

Costs of using virtual function Each object has its size increased by the amount needed to hold an address For each class, the compiler creates a table (an array) of addresses of virtural functions For each function call, there’s an extra step of going to a table to look up an address

Rules of virtual methods Begin a class method declaration with the keyword virtual in a base class Constructor cannot be virtual Destructor should be virtual unless a class isn’t to be used as a base class Friends cannot be virtual functions because friends are not class members Statics cannot be virtual If a derived class fails to redefine a function, the class will use the base version of the function If base class declaration is overloaded, one needs to redefine all the base class version in derived class

Return type is allowed to vary

Redefinition hides methods

Hidden methods

Inheritance is-a relationship Sometimes applying the is-a rule is not as simple as it might appear For example, A circle is a special case of an ellipse. Problems arise when one is tempting to derive a circle class from an ellipse class.

Abstract base classes (ABC) Solution: One can abstract from the Ellipse and Circle classes what they have in common and place those features in an ABC Program acctabc.h, acctabc.cpp, usebrass3.cpp

Inheritance & dynamic memory allocation How does inheritance interact with dynamic memory allocation? Derived class doesn’t use new Derived class does use new

Derived class without DMA It is not necessary to self-defined constructors, copy constructor, destructor, assignment by using new and delete

Derived class with DMA It needs to self-defined constructors, copy constructor, destructor, assignment by using new and delete

An inheritance example with DMA and Friends Program dma.h, dma.cpp, usedma.cpp

Class design Member functions that the compiler generates for you –Default constructors –Copy constructors –Assignment operators –Destructors Class method considerations

Constructor –Constructors aren’t inherited) Destructor –Should provide virtual destructor in base class Conversion constructors

Passing by value or reference Passing an object by value or passing by reference –Passing by value involves a temporary copy constructor and then destructor –Efficiency sake –Inheritance using virtual function to accept a base-class reference argument

Returning an object or returning a reference

Public inheritance considerations Is-a relationship consideration Constructors are not inherited Down casting is not safe Assignment operator // Implicit upcast // Explicit downcast // Save upcast // Unsafe downcast Or use conversion constructor

Public/private/protected members private protected public Class D: protected A D ObjD private protected public Class DD: public D DD ObjDD private protected public Class CC: public C CC ObjCC

Virtual method considerations Inappropriate code In the Inadequate() function Brass version ViewAcct() was called Brace object constructed by Brass copy constructor Automatic upcasting allows the constructor argument to refer to a BrassPlus object

Other methods considerations A base class destructor should be virtual Friend function is not actually a class member, it is not inherited

The base class methods in public inheritance

Member functions in class