Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.

Slides:



Advertisements
Similar presentations
Constructors: Access Considerations DerivedClass::DerivedClass( int iR, float fVar) : BaseClass(fVar) { m_uiRating = uiR; } Alternatively DerivedClass::DerivedClass(
Advertisements

V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation - a language mechanism for restricting access to some.
Inheritance and Polymorphism CS351 – Programming Paradigms.
1 CSE 303 Lecture 24 Inheritance in C++, continued slides created by Marty Stepp
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.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
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.
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.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
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.
 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.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.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.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Object-Oriented Programming Chapter Chapter
Object Oriented Programming
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.
ISBN Object-Oriented Programming Chapter Chapter
CS212: Object Oriented Analysis and Design Lecture 16: Runtime Polymorphism.
Inheritance and Composition Reusing the code and functionality Unit - 04.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 18: More on inheritance and 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.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Copyright © 2012 Pearson Education, Inc. Chapter 10 Advanced Topics.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
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.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
CPSC 252Inheritance II Page 1 Inheritance & Pointers Consider the following client code: const int MAXCLOCKS = 2; Clock* clockPtr[ MAXCLOCKS ]; clockPtr[0]
C#.Net Software Development Version 1.0. Overview Inheritance Member Access Constructors Polymorphism (Name Hiding) Multilevel Hierarchy Virtual and VTable.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
7. Inheritance and Polymorphism
Polymorphism &Virtual Functions
Class A { public : Int x; A()
Polymorphism.
Inheritance and Run time Polymorphism
CS212: Object Oriented Analysis and Design
Polymorphism & Virtual Functions
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism Lec
Virtual Functions Department of CSE, BUET Chapter 10.
Polymorphism Polymorphism
CISC/CMPE320 - Prof. McLeod
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Binding 10: Binding Programming C# © 2003 DevelopMentor, Inc.
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.
Presentation transcript:

Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes

Modern Object-Oriented Concepts  Modern object-oriented (OO) languages provide 3 capabilities: —encapsulation —inheritance —polymorphism which can improve the design, structure and reusability of code.

Inheritance in C++  Syntax: class X : public Y FuncChild( type x ) : FuncParent( x ) { }  Example: — class Manager: public Employee

public, protected and private  as access specifier of class members: —public: everyone who knows the class can access the member —protected: only the class itself and its children can access the member —private: no one but the class itself can access the member  as inheritance specifier: —public: everyone who knows the Base and Child also know the inheritance relation. —protected: only Child and its children knows the inheritance relation. —private: no one other than Child knows the inheritance relation.  We only use public inheritance in this course! —This guarantees all the public data and methods from the base class remain public in the derived class.

What is inherited?  In principle, a derived class inherits every member of a base class except: —its constructor and its destructor —its operator=() members —its friends  Although the constructors and destructors of the base class are not inherited themselves, its default constructor (i.e., its constructor with no parameters) and its destructor are always called when a new object of a derived class is created or destroyed.  What if the base class has no default constructor?  Can a derived class access private members of the base class?

Member Initialization List  For class constructors only  can be used to overload constructors Manager::Manager(string n, float rate, bool isSalaried ) : Employee( n, rate ) { salaried = isSalaried; }  can be used to initialize data members in constructors Employee(string n, float rate ) : Person( n ), payRate(rate) {}

Multiple Inheritance  In C++ it is possible that a class inherits members from more than one class. class Son: public Mother, public Father;  However, it smells! —You will learn more details in later design classes.  See the example on the course page.

Polymorphism  polymorphism means that some code or operations or objects behave differently in different contexts.  How to decide? —static binding: at compilation time (overloading) —dynamic binding: at run time (virtual functions)  C++ uses virtual functions to implement dynamic binding. —when the term polymorphism is used with C++, it refers to using virtual functions

Base Class Pointer  We can assign a pointer to a derived class to a variable declared using the base class Employee * emp; emp = new Manager( name, rate, true ); cout Name() Pay( hours ) << endl;  By default, it is the type of the pointer (i.e., Employee), not the type of the object it points to (i.e., possibly Manager) that determines which version will be called.  How to call Manager ::Pay( hours ) ? —Make Employee ::Pay( int hours ) virtual! virtual float Pay( float hoursWorked ) const;

Virtual Function  A member of a class that can be redefined in its derived classes is known as a virtual member. —precede its declaration with the keyword virtual  Once a method is declared as virtual, it is virtual in all derived classes too.  Destructors should always be virtual! (See example)  Constructors are never virtual! Why?

vtable  A virtual method/function/call table is to support run-time method binding. —contains pointers to virtual functions  Typically, the compiler creates a separate vtable for each class.  When an object is created, a pointer to this vtable, called the virtual table pointer, vpointer or VPTR, is added as a hidden member of this object.  For any class that contains a vtable, the compiler will also add "hidden" code to the constructor of that class to initialize the vpointers of its objects to the address of the corresponding vtable.

vtable example class C { public: virtual void f(); void g(); virtual void h(); }; class D : public C { public: void f(); void u(); virtual void v(); }; C cObj; D dObj; vtable for C: +0: C::f() // pointer +4: C::h() vtable for D: +0: D::f() // f is overloaded +4: C::h() // h is not +8: D::v()

Abstract Base Class  No keyword “abstract” in C++  To make an abstract class, include at least one pure virtual function. virtual int GetValue() = 0;  An abstract class cannot be instantiated!  any derived class must define a body for the pure virtual function, or that derived class will be considered an abstract base class as well.  An interface can be implemented in C++ as an abstract base class with only pure virtual functions.

Example class IntContainer { public: IntContainer() : count(0) { } virtual void add(int x) = 0; virtual void remove(int x) = 0; virtual bool contains(int x) const = 0; int size() const { return count; } protected: int count; }; class IntSet : public IntContainer { public: void add(int x); void remove(int x); bool contains(int x); protected: int *nums; // growable array }; IntContainer cont1; // ILLEGAL! IntContainer *cont2; // (legal) cont2 = new IntContainer; // ILLEGAL! cont2 = new IntSet; // (legal)

Type Cast of Objects  Explicit conversion: Employee * emp; Manager * m = (Manager*)(emp);  Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member functions may produce either a run-time error or a unexpected result.  dynamic_cast (expression)  static_cast (expression)  reinterpret_cast (expression)  const_cast (expression)

static_cast  perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived.  can also be used to perform any other non-pointer conversion  ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. —it is up to the programmer to ensure that the conversion is safe. class CBase {}; class CDerived: public CBase {}; CBase * a = new CBase; CDerived * b = static_cast (a);

dynamic_cast  used only with pointers and references to objects.  Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class. —always successful when we cast a class to one of its base classes CBase b; CBase* pb; CDerived d; CDerived* pd; pb = dynamic_cast (&d); // ok: derived-to-base pd = dynamic_cast (&b); // wrong: base-to-derived