QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

Size: px
Start display at page:

Download "QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?"

Transcription

1 QUIZ Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

2

3 Or Foo(x), depending on how we want the initialization to be made.

4

5 Criticize!

6 Ch. 15: Polymorphism & Virtual Functions

7 text Virtual functions enhance the concept of type. There is no analog to the virtual function in a traditional procedural language. As a procedural programmer, you have no referent with which to think about virtual functions, as you do with almost every other feature in the language. Features in a procedural language can be understood on an algorithmic level, but, in an OOL, virtual functions can be understood only from a design viewpoint.

8 Remember upcasting

9 Draw the UML diagram!

10 We would like the more specific version of play() to be called, since flute is a Wind object, not a generic Instrument.

11 Ch. 1: Introduction to Objects Remember from ch.1

12 text Early binding vs. late binding The C++ compiler inserts a special bit of code in lieu of the absolute call. This code calculates the address of the function body, using information stored in the object at runtime!

13 Ch. 15: Polymorphism & Virtual Functions

14 text virtual functions To cause late binding to occur for a particular function, C++ requires that you use the virtual keyword when declaring the function in the base class. All derived-class functions that match the signature of the base-class declaration will be called using the virtual mechanism. example

15 It is legal to also use the virtual keyword in the derived-class declarations, but it is redundant and can be confusing.

16 text Extensibility With play( ) defined as virtual in the base class, you can add as many new types as you want without changing the tune( ) function. In a well-designed OOP program, most or all of your functions will follow the model of tune( ) and communicate only with the base-class interface. Such a program is extensible because [ ] the functions that manipulate the base-class interface will not need to be changed at all to accommodate the new classes.

17 Read and understand the full program C15:Instrument4.cpp

18 text How C++ implements late binding The typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object.

19 If function is not overridden in the base class, the address of its base-class version is placed in the VTABLE.

20 Here s what a call to adjust( ) for a Brass object looks like, if made through an Instrument pointer: (An Instrument reference produces the same result) The memory overhead is only one pointer, no matter how many virtual functions there are!

21 Installing the vpointer This is where the default constructor is essential: In the Instrument examples, the compiler creates a default constructor that does nothing except initialize VPTR. This constructor, of course, is automatically called for all Instrument objects before you can do anything with them, so you know that it s always safe to call virtual functions.

22 Objects are different early binding? and references? [ ] upcasting deals only with addresses (?) Means: Upcasting is not necessarily implemented by the compiler via late binding. Actually, if given the choice, the compiler will probably prefer early binding, since it results in faster code. But when the compiler does not have the object (i.e. when the object is passed by pointer or reference), it must use late binding. Code example

23

24 Abstract base classes and pure virtual functions Often in a design, you want the base class to present only an interface for its derived classes. That is, you don t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used. We say that the virtual function is pure.

25 A class with only pure virtual functions is called a pure abstract class. These functions exist only to create a common interface for all the derived classes. Code example

26 The compiler still reserves a slot for a pure virtual function in the VTABLE, but does not to put an address in that particular slot.

27 QUIZ Write a pure virtual function foo in the parent class, and redefine it as a virtual function in the child class.

28 QUIZ In practical terms, what is the difference between a virtual function and a pure virtual one?

29 Solution In practical terms, what is the difference between a virtual function and a pure virtual one? A: If a class has a pure virtual function, no objects of that class can be instantiated.

30 QUIZ Does this code compile? (Assume that Abstract::bar and Derived::foo are defined in another file.) int main(){ Derived d; } Source:

31 Solution Yes. A derived class does not need to override virtual functions from the parent, only pure virtual ones! int main(){ Derived d; }

32 Actually, not every derived class needs to override the pure virtuals from the parent! A function can stay pure virtual in several levels of the hierarchy. (But, eventually, all pure virtuals must be overriden in order to be able to instantiate objects.) int main(){ DerivedMore dm; }

33 Virtual functions in multi-level hierarchies

34 Individual work for next time: Read and understand the section Under the hood Why virtual functions? End-of-chapter exercise 1 EOL 1

35 QUIZ How is the late binding of virtual functions implemented in the C++ compiler?

36 text How C++ implements late binding The typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object.

37 QUIZ Why do we need virtual functions?

38 text virtual functions To cause late binding and upcasting to occur for a particular function, C++ requires that you use the virtual keyword when declaring the function in the base class. All derived-class functions that match the signature of the base-class declaration will be called using the virtual mechanism.

39 QUIZ Why do we need pure virtual functions?

40 Abstract base classes and pure virtual functions Often in a design, you want the base class to present only an interface for its derived classes. That is, you don t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used. We say that the virtual function is pure.

41 Common misconception: It s illegal to provide a definition for a pure virtual function But, wait a second: If we cannot instantiate objects of type Abstract, what use can the definition be?

42 It is legal to provide a definition for a pure virtual function! We can always access the parent function using the scope resolution operator!

43 however, the pure virtual function definition cannot be inline:

44 QUIZ: Show how to access the Pet pure virtual code in main

45 Inheritance and the VTABLE It is also possible to add new virtual functions to the derived class. example

46

47 VTABLEs created by the compiler for Pet and Dog:

48 VTABLEs created by the compiler for Pet and Dog: Problem: We cannot use sit() with an upcast pointer or reference!

49 This is the opposite of upcasting It is called downcasting.

50 Solution: typecast manually!

51 Extra-credit quiz

52 Ch. 3: The C in C++

53 C++ explicit casts Back to Ch.15

54 Run-time type identification (RTTI) RTTI is all about casting base-class pointers down to derived-class pointers ( up and down are relative to a typical class diagram, with the base class at the top). Casting up happens automatically, with no coercion, because it s completely safe. Casting down is unsafe because there s no compile time information about the actual types, so you must know exactly what type the object is. If you cast it into the wrong type, you ll be in trouble.

55 Run-time type identification (RTTI) dynamic_cast does its work at runtime, using the virtual table It tends to be more expensive than the other C++-style casts.

56 QUIZ Is this use of the function sit( ) correct? Explain.

57 Solution Is this use of the function sit() correct? Explain. Yes. Remember that, when the compiler has the actual object, it uses early binding, so the VTABLE never comes into play.

58 Polymorphism - definition It is the virtual function mechanism described in this chapter, involving the VTABLE, VPTRs, upcasting, downcasting and RTTI. It allows late binding to occur.

59 Object slicing or Why we should not use pass-byvalue with polymorphism

60

61 Do you remember how parameters are passed to a function? An object the size of Pet is pushed on the stack (and cleaned up after the call)

62 Fluffy is sliced

63 Do. Not. Slice. Fluffy. Object slicing actually removes part of the object as it copies it into the new object (rather than simply changing the meaning of an address, as when using a pointer or reference). Because of this, upcasting into an object is not done often; in fact, it s usually something to watch out for and prevent.

64 Overloading & overriding In Chapter 14, we learned that redefining an overloaded function in the base class hides all of the other base-class versions of that function. When virtual functions are involved the behavior is a little different.

65 The base class is expecting an int to be returned from f( ). The derived-class version of f( ) must keep that contract!

66 Does this mean that we cannot modify the return type of a virtual function during overriding?

67 In general, yes! Does this mean that we cannot modify the return type of a virtual function during overriding? but there is a special case in which we can slightly modify the return type: If returning a pointer or a reference to a base class, the overridden version of the function may return a pointer or reference to a class derived from that base. This is called

68 Variant return type Note: Returning the base type will generally solve your problems so this is a rather specialized feature. This is another application of dynamic_cast!

69 Same as in base class, no new rule need aply. Draw the UML class diagram! The variant type rule allows this: The return type is more derived than in the base class (but inherited from it!!)

70

71 Example user code No problem, the two types agree. Need a downcast (less safe!)

72 We stop before the section virtual functions & constructors and we skip the remainder of this chapter. Individual work / review for Ch.15: End-of-chapter exercises 2, 3 EOL 2

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University Polymorphism Miri Ben-Nissan (Kopel) 1 Shape Triangle Rectangle Circle int main( ) Shape* p = GetShape( ); p->draw( ); Shape* GetShape( ) choose randomly which shape to send back For example: Shape* p

More information

15: Polymorphism & Virtual Functions

15: Polymorphism & Virtual Functions 15: Polymorphism & Virtual Functions 김동원 2003.02.19 Overview virtual function & constructors Destructors and virtual destructors Operator overloading Downcasting Thinking in C++ Page 1 virtual functions

More information

Object-Oriented Programming

Object-Oriented Programming iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 40 Overview 1 2 3 4 5 2 / 40 Primary OOP features ion: separating an object s specification from its implementation. Encapsulation: grouping related

More information

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. QUIZ How

More information

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. Ch. 14: Inheritance

More information

Inheritance, Polymorphism and the Object Memory Model

Inheritance, Polymorphism and the Object Memory Model Inheritance, Polymorphism and the Object Memory Model 1 how objects are stored in memory at runtime? compiler - operations such as access to a member of an object are compiled runtime - implementation

More information

Polymorphism. Zimmer CSCI 330

Polymorphism. Zimmer CSCI 330 Polymorphism Polymorphism - is the property of OOP that allows the run-time binding of a function's name to the code that implements the function. (Run-time binding to the starting address of the code.)

More information

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017 OOP components For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Chapter 15. Polymorphism and Virtual Functions. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 15. Polymorphism and Virtual Functions. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 15 Polymorphism and Virtual Functions Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Virtual Function Basics Late binding Implementing virtual functions When to

More information

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University (12-1) OOP: Polymorphism in C++ D & D Chapter 12 Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University Key Concepts Polymorphism virtual functions Virtual function tables

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

Virtual functions concepts

Virtual functions concepts Virtual functions concepts l Virtual: exists in essence though not in fact l Idea is that a virtual function can be used before it is defined And it might be defined many, many ways! l Relates to OOP concept

More information

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck C++ Crash Kurs Polymorphism Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Polymorphism Major abstractions of C++ Data abstraction

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

QUIZ Friends class Y;

QUIZ Friends class Y; QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They

More information

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING YEAR/SEM:II & III UNIT I 1) Give the evolution diagram of OOPS concept. 2) Give some

More information

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file? QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Polymorphism. Hsuan-Tien Lin. OOP Class, April 8, Department of CSIE, NTU. H.-T. Lin (NTU CSIE) Polymorphism OOP 04/08/ / 26

Polymorphism. Hsuan-Tien Lin. OOP Class, April 8, Department of CSIE, NTU. H.-T. Lin (NTU CSIE) Polymorphism OOP 04/08/ / 26 Polymorphism Hsuan-Tien Lin Department of CSIE, NTU OOP Class, April 8, 2013 H.-T. Lin (NTU CSIE) Polymorphism OOP 04/08/2013 0 / 26 Polymorphism: The Motto One Thing, Many Shapes... H.-T. Lin (NTU CSIE)

More information

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

04-24/26 Discussion Notes

04-24/26 Discussion Notes 04-24/26 Discussion Notes PIC 10B Spring 2018 1 When const references should be used and should not be used 1.1 Parameters to constructors We ve already seen code like the following 1 int add10 ( int x

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Inheritance. Overview. Chapter 15 & additional topics. Inheritance Introduction. Three different kinds of inheritance

Inheritance. Overview. Chapter 15 & additional topics. Inheritance Introduction. Three different kinds of inheritance Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Motivating

More information

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova You reuse code by creating new classes, but instead of creating them from scratch, you use existing classes that someone else has built and debugged. In composition

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 Data Structures Course Review FINAL Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Final When: Wednesday (12/12) 1:00 pm -3:00 pm Where: In Class

More information

Lecturer: William W.Y. Hsu. Programming Languages

Lecturer: William W.Y. Hsu. Programming Languages Lecturer: William W.Y. Hsu Programming Languages Chapter 9 Data Abstraction and Object Orientation 3 Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Inheritance Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting.

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting. 7. Polymorphism 1 Upcasting Taking an object reference and treating it as a reference to its base type is called upcasting. class Instrument { public void play () { public class Wind extends Instrument

More information

CS11 Introduction to C++ Fall Lecture 7

CS11 Introduction to C++ Fall Lecture 7 CS11 Introduction to C++ Fall 2012-2013 Lecture 7 Computer Strategy Game n Want to write a turn-based strategy game for the computer n Need different kinds of units for the game Different capabilities,

More information

Polymorphism and Inheritance

Polymorphism and Inheritance Walter Savitch Frank M. Carrano Polymorphism and Inheritance Chapter 8 Objectives Describe polymorphism and inheritance in general Define interfaces to specify methods Describe dynamic binding Define and

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Inheritance Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

Object Oriented Programming with c++ Question Bank

Object Oriented Programming with c++ Question Bank Object Oriented Programming with c++ Question Bank UNIT-1: Introduction to C++ 1. Describe the following characteristics of OOP. i Encapsulation ii Polymorphism, iii Inheritance 2. Discuss function prototyping,

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

Increases Program Structure which results in greater reliability. Polymorphism

Increases Program Structure which results in greater reliability. Polymorphism UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the

More information

1: Introduction to Object (1)

1: Introduction to Object (1) 1: Introduction to Object (1) 김동원 2003.01.20 Overview (1) The progress of abstraction Smalltalk Class & Object Interface The hidden implementation Reusing the implementation Inheritance: Reusing the interface

More information

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Design issues for objectoriented. languages. Objects-only pure language vs mixed. Are subclasses subtypes of the superclass? Encapsulation Encapsulation grouping of subprograms and the data they manipulate Information hiding abstract data types type definition is hidden from the user variables of the type can be declared variables

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

QUIZ How do we implement run-time constants and. compile-time constants inside classes? QUIZ How do we implement run-time constants and compile-time constants inside classes? Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of

More information

Inheritance STL. Entity Component Systems. Scene Graphs. Event Systems

Inheritance STL. Entity Component Systems. Scene Graphs. Event Systems Inheritance STL Entity Component Systems Scene Graphs Event Systems Event Systems Motivation: Decoupling events from where they are sent and where they are processed. It facilitates communication between

More information

Project. C++: Inheritance III. Plan. Project. Before we begin. The final exam. Advanced Topics. Project. This week in the home stretch

Project. C++: Inheritance III. Plan. Project. Before we begin. The final exam. Advanced Topics. Project. This week in the home stretch Project C++: III Advanced Topics Othello submitted. Next submission: Team Evaluations Nov 10 th Please don t forget If solo give yourself a good evaluation! Indicate if okay to share feedback with partner

More information

Chapter 2: Java OO II X I A N G Z H A N G

Chapter 2: Java OO II X I A N G Z H A N G Chapter 2: Java OO II X I A N G Z H A N G j a v a c o s e @ q q. c o m Content 2 Abstraction Abstract Class Interface Inheritance Polymorphism Abstraction What is Abstraction? Abstraction 4 An abstraction

More information

Dynamic Binding C++ Douglas C. Schmidt

Dynamic Binding C++ Douglas C. Schmidt Dynamic Binding C++ Douglas C. Schmidt Professor Department of EECS d.schmidt@vanderbilt.edu Vanderbilt University www.dre.vanderbilt.edu/schmidt/ (615) 343-8197 Motivation When designing a system it is

More information

Lecture Notes on Programming Languages

Lecture Notes on Programming Languages Lecture Notes on Programming Languages 85 Lecture 09: Support for Object-Oriented Programming This lecture discusses how programming languages support object-oriented programming. Topics to be covered

More information

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented

More information

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++ Session 6 - Inheritance in C++ The most important slide of the lecture Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Why use inheritance?

More information

This wouldn t work without the previous declaration of X. This wouldn t work without the previous declaration of y

This wouldn t work without the previous declaration of X. This wouldn t work without the previous declaration of y Friends We want to explicitly grant access to a function that isn t a member of the current class/struct. This is accomplished by declaring that function (or an entire other struct) as friend inside the

More information

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Inheritance. Chapter 15 & additional topics

Inheritance. Chapter 15 & additional topics Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Inheritance

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

OOP THROUGH C++(R16) int *x; float *f; char *c;

OOP THROUGH C++(R16) int *x; float *f; char *c; What is pointer and how to declare it? Write the features of pointers? A pointer is a memory variable that stores the address of another variable. Pointer can have any name that is legal for other variables,

More information

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading How C++ Works 1 Overview Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading Motivation There are lot of myths about C++

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

CIS 190: C/C++ Programming. Lecture 11 Polymorphism

CIS 190: C/C++ Programming. Lecture 11 Polymorphism CIS 190: C/C++ Programming Lecture 11 Polymorphism 1 Outline Review of Inheritance Polymorphism Limitations Virtual Functions Abstract Classes & Function Types Virtual Function Tables Virtual Destructors/Constructors

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information

Inclusion Polymorphism

Inclusion Polymorphism 06D-1 Inclusion Polymorphism Polymorphic code Polymorphic references Up- and Down- Casting Polymorphism and values Polymorphic Arrays Inclusion Polymorphism in Context 06D-2 Polymorphism Ad hoc Universal

More information

CMSC202 Computer Science II for Majors

CMSC202 Computer Science II for Majors CMSC202 Computer Science II for Majors Lecture 14 Polymorphism Dr. Katherine Gibson Last Class We Covered Miscellaneous topics: Friends Destructors Freeing memory in a structure Copy Constructors Assignment

More information

Reusable and Extendable Code. Composition Example (1) Composition Example (2) CS183-Su'02-Lecture 8 17 June by Eric A. Durant, Ph.D.

Reusable and Extendable Code. Composition Example (1) Composition Example (2) CS183-Su'02-Lecture 8 17 June by Eric A. Durant, Ph.D. Reusable and Extendable Code Tools so far classes ADTs using classes Building new classes Composition class objects as data members Inheritance Extending an existing class 1 Composition Example (1) class

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis? Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator

More information

Object-Oriented Concept

Object-Oriented Concept Object-Oriented Concept Encapsulation ADT, Object Inheritance Derived object Polymorphism Each object knows what it is Polymorphism noun, the quality or state of being able to assume different forms -

More information

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University February 11, 2008 / Lecture 4 Outline Course Status Course Information & Schedule

More information

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a. Intro to OOP - Object and class - The sequence to define and use a class in a program - How/when to use scope resolution operator - How/when to the dot operator - Should be able to write the prototype

More information

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction Lecture 13: Object orientation Object oriented programming Introduction, types of OO languages Key concepts: Encapsulation, Inheritance, Dynamic binding & polymorphism Other design issues Smalltalk OO

More information

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading HOW C++ WORKS Overview Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading Motivation There are lot of myths about C++

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

Concepts of Programming Languages

Concepts of Programming Languages Concepts of Programming Languages Lecture 10 - Object-Oriented Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages

More information

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright Polymorphism Object Orientated Programming in Java Benjamin Kenwright Quizzes/Labs Every single person should have done Quiz 00 Introduction Quiz 01 - Java Basics Every single person should have at least

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Inheritance Ch

Inheritance Ch Inheritance Ch 15.1-15.2 Announcements Test graded! Highlights - Creating parent/child classes (inheritance) -protected Story time Story time Story time Story time Story time Derived classes Let's make

More information