ECE 3574: Dynamic Polymorphism using Inheritance

Similar documents
Inheritance, Polymorphism and the Object Memory Model

Java Object Oriented Design. CSC207 Fall 2014

Lecture 5: Inheritance

OBJECT ORIENTED PROGRAMMING USING C++

Polymorphism Part 1 1

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

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

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

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

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

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

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

What about Object-Oriented Languages?

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Data Abstraction. Hwansoo Han

CS11 Advanced C++ Fall Lecture 7

Programming in C# Inheritance and Polymorphism

C++ Important Questions with Answers

Chapter 5 Object-Oriented Programming

Inheritance, and Polymorphism.

CSE 307: Principles of Programming Languages

Object-oriented Programming. Object-oriented Programming

C++ Programming: Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism

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

G Programming Languages - Fall 2012

What is Inheritance?

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Inheritance: Develop solutions by abstracting real-world object and their interaction into code to develop software solutions. Layering: Organization

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Inheritance and Polymorphism

Object Oriented Programming. Solved MCQs - Part 2

Inheritance and Polymorphism

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

C++ Inheritance and Encapsulation

And Even More and More C++ Fundamentals of Computer Science

CS OBJECT ORIENTED PROGRAMMING

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Computer Science II CSci 1200 Lecture 24 C++ Inheritance and Polymorphism

CS105 C++ Lecture 7. More on Classes, Inheritance

CS 162, Lecture 25: Exam II Review. 30 May 2018

Chapter 1: Object-Oriented Programming Using C++

CS11 Introduction to C++ Fall Lecture 7

Increases Program Structure which results in greater reliability. Polymorphism

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

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

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

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

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

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

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

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

SERIOUS ABOUT SOFTWARE. Qt Core features. Timo Strömmer, May 26,

Inheritance and object compatibility

CSE 12 Week Eight, Lecture One

Tokens, Expressions and Control Structures

CPS 506 Comparative Programming Languages. Programming Language

Inheritance -- Introduction

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

Polymorphism. Arizona State University 1

Object-Oriented Concepts and Design Principles

Inheritance and Polymorphism

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

C++ Alexander Baltatzis

Lecture Notes on Programming Languages

C++ Casts and Run-Time Type Identification

CS-202 Introduction to Object Oriented Programming

Polymorphism and Interfaces. CGS 3416 Spring 2018

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

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

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

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

COSC252: Programming Languages: Abstraction and OOP. Jeremy Bolton, PhD Asst Teaching Professor. Copyright 2015 Pearson. All rights reserved.

Polymorphism. Zimmer CSCI 330

OBJECT ORIENTED PROGRAMMING

Object Oriented Programming

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Instantiation of Template class

Chapter 10 Classes Continued. Fundamentals of Java

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

Chapter 14 Abstract Classes and Interfaces

CS304 Object Oriented Programming Final Term

Programming II (CS300)

CSCI-1200 Data Structures Fall 2017 Lecture 25 C++ Inheritance and Polymorphism

Computer Programming Inheritance 10 th Lecture

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

CS111: PROGRAMMING LANGUAGE II

C++ (classes) Hwansoo Han

Absolute C++ Walter Savitch

CLASSES AND OBJECTS IN JAVA

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

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Inheritance and Interfaces

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

IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class

CSc 520. Principles of Programming Languages 45: OO Languages Introduction

C++ Inheritance II, Casting

Object Oriented Programming. Java-Lecture 11 Polymorphism

Programming II (CS300)

Transcription:

1 ECE 3574: Dynamic Polymorphism using Inheritance Changwoo Min

2 Administrivia Survey on class will be out tonight or tomorrow night Please, let me share your idea to improve the class!

3 Meeting 10: Dynamic Polymorphism using Inheritance Today we will learn more about code reuse via dynamic polymorphism. Subtyping and Object Hierarchies Abstract Base Classes as Interfaces Dynamic Casting Qt Object Model Qt Ownership Examples There is no exercise today.

4 C++ Inheritance and Base Classes C++ has several mechanisms to reuse code. One of them is polymorphism (many-form), where a class can inherit methods from one or more other classes. Polymorphism means selecting what code to run based on the type.

5 Classic Shape Example Suppose we wanted to have classes that model closed 2D shapes. There are things that every 2D shape has, for example a perimeter. We can ensure that any class that implements a specific 2D shape has an appropriate method by first defining a base class class Shape2DBase { public: virtual double perimeter() = 0; };

6 Classic Shape Example class Shape2DBase { public: virtual double perimeter() = 0; // abstract virtual function }; void main(void) { Shape2DBase shape; // compiler error! } virtual : virtual function it can be redefined in subclasses = 0 : abstract virtual function (similar to interface in Java) this class does not provide an implementation on purpose we can t instantiate such a class

7 Classic Shape Example We can define and implement a setup of classes that conform to the base class using public inheritance (there are other kinds we are ignoring for now). For example we might define a Circle as class Circle: public Shape2DBase // public inheritance of Shape2DBase { public: Circle(double r): radius(r) {}; double perimeter() { // overriding of the abstract virtual function return 2*M_PI*radius; } private: const double radius; }; We might continue with classes for Square, Rectangle, Ellipse, etc.

8 Classic Shape Example This is handy because, while I can t instantiate the Shape2DBase, I can a pointer or a reference to one. So I could define a function that works for any subclass of Shape2DBase (lets say I want to show the perimeter). I can then pass a Circle, Square, etc to the function. Since it knows the classes have a perimeter method it can call it. Example void show_perim(shape2dbase & shape) { std::cout << "Perimeter = " << shape.perimeter() << std:: } void main() { Circle c1(1.0); show_perim(c1); }

9 Templates versus Base Classes You might have noticed this looks similar to templates. For example I could define Circle, Square, etc without inheritance but till defining a perimeter method, then define the function as a template. The difference is one between runtime and compile time, or dynamic versus static polymorphism. template<typename T> void show_perim(t & shape) { std::cout << "Perimeter = " << shape.perimeter() << std:: }

10 Dynamic versus static polymorphism Static polymorphism (also called compile-time polymorphism): Pro: can check assumptions at compile time Pro: allows the compiler to optimize Con: leads to larger binary code, cannot switch code at runtime Dynamic polymorphism (also called Subtyping): Pro: allows switching at runtime (for example based on input) Pro: has smaller binary size Con: requires runtime/dynamic casting Con: can t selectively optimize sine it happens after compilation

11 Polymorphism means selecting what code to run based on the type Dynamic polymorphism means the selection happens at runtime. The basic language mechanisms are: Inheritance or Derivation Virtual Functions, also called dynamic dispatch or runtime dispatch (virtual function table per class) Encapsulation via private/public

12 Inheritance allows us to build one class from another Represents an "is-a" relationship. A Circle is a Shape. You specify the base class after declaring the derived class as class BaseClass {}; class DerivedClass: public BaseClass {};

13 Inheritance allows us to build one class from another The public part means that the public members of BaseClass are inherited and become public members of DerivedClass. Note the above is equivalent to since struct members are public by default. Example: inherit.cpp class BaseClass {}; class DerivedClass: BaseClass {};

14 Review: private, protected, and public members that are private can only be accessed by members in the same class members that are protected can only be accessed by members in the same class and those derived from it members that are public can be accessed by any functions struct : a class that all members are public Note, this simplified version ignores friend access

15 private, protected, and public inheritance private inheritance means that the public and protected members of the base class can only be used by the derived class protected inheritance means that the public and protected members of the base class can only be used by the derived class and any classes derived from it public inheritance means that the public members of the base class can be used by any function Note, there is no way to inherit the private members of a class.

16 Summary: private inheritance class BaseClass {}; class DerivedClass: private BaseClass {}; It means that the the public and protected members of BaseClass become private members of DerivedClass. This is less common than the others, but can be useful for writing adapters.

17 Summary: protected inheritance class BaseClass {}; class DerivedClass: protected BaseClass {}; It means that the the public and protected members of BaseClass become protected members of DerivedClass. This is used for keeping functionality within the tree of objects.

18 Summary: public inheritance class BaseClass {}; class DerivedClass: public BaseClass {}; It means that the the public members of BaseClass become public members of DerivedClass. This is the most used, and presents the client code with a polymorphic interface.

19 A graphical view Inheritance allow you to specify a tree relationship among types

20 Virtual Functions Declaring a method virtual means that it can be overridden in the DerivedClass, but need not be. Note that you can redefine the method in DerivedClass even if it is not marked virtual, but it will not be called when represented as the BaseClass. This is a source of much pain. If you intend for a method to be overridden, mark it as virtual. Note the virtual keyword is not used in the implementation if outside the class definition.

21 Abstract Virtual Functions To force the derived class to implement the method you make it pure as struct BaseClass { virtual void amethod() = 0; }; Abstract virtual function = pure virtual function Similar to interface in Java Take care when overriding that the name and arguments match.

22 C++ allows multiple inheritance class Base1 {}; class Base2 {}; class Derived: ACCESS Base1, ACCESS Base2 where ACCESS can be private, protected, or public. This feature is much maligned because it creates confusion around what gets inherited. It is useful though for defining an interface. Multiple inheritance other than interface is a code smell See Qt class hierarchy Example: multiple.cpp

23 An interface is a base class with only pure virtual methods This allows you to express that a class implements that interface explicitly, and the compiler verifies that it at least implements the methods. When used with multiple inheritance this allows you to express that some parts of an object tree implement a certain interface. Example: ADT_interface.h

24 Heterogeneous Collections using a Base Type Since a pointer or reference to a base object can actually refer to a derived object, you can defined containers of mixed type (within the object hierarchy) Example: collections.cpp

25 Dynamic Casting Given a pointer to a base class you can attempt to convert it back to a derived type using dynamic_cast. This works for up-cat (but is unnecessary), down-cast, and sideways-cast. Example: casting.cpp Type conversions in C++ dynamic_cast<>, static_cast<>, reinterpret_cast<>, const_cast<>, and typeid()

26 An important point: any base class should define its destructor as virtual If you don t then if you call delete on a base pointer to a derived object, the derived destructor is not called. any class designed to be used as a base class will have a virtual destructor I repeat, do not derive from a class that has a non-virtual destructor. Example: virtual.cpp ECPP: Item 7: Declare destructors virtual in polymorphic base classes

27 Some remarks about dynamic polymorphism There are many places for bugs to hide Don t get carried away with defining object hierarchies. Excessive casting is a code smell

28 Uses of Dynamic Polymorphism Dynamic Polymorphism is very useful when you want to treat objects (instances of classes) as hierarchical data. Graphical user interfaces are ideally suited to polymorphism. They are just trees of widgets. Code to layout and draw widgets should be independent of the specific interface. Rendering of dynamic objects, for example in simulations or games, should be independent of the specific objects involved. Employees are people that have categories and form departments, units, divisions, etc.

29 Qt Object Hierarchy In Qt QObject is the base of everything. This is critical to how the properties and signals/slots are implemented. So, any class you write that needs to communicate with Qt should derive from QObject. Simple example: a class that can receive a print signal from another QObject. class Printer: public QObject { Q_OBJECT public slots: void print(); };

30 Qt Memory Ownership Qt objects form trees so that each object has a parent. Heap allocated objects are owned by their parents and destroyed when their parents are. For stack allocated objects take care the parent object is instantiated before children.

31 Next Actions and Reminders Read about Composition