Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

Similar documents
CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

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

Polymorphism. Arizona State University 1

VIRTUAL FUNCTIONS Chapter 10

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

ECE 122. Engineering Problem Solving with Java

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

Chapter 14 Abstract Classes and Interfaces

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

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

C++ Inheritance and Encapsulation

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

Instantiation of Template class

Object Oriented Programming. Java-Lecture 11 Polymorphism

Java Object Oriented Design. CSC207 Fall 2014

Lecture 5: Inheritance

Object-Oriented Programming More Inheritance

G52CPP C++ Programming Lecture 20

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

Inheritance, and Polymorphism.

Extending Classes (contd.) (Chapter 15) Questions:

Fast Introduction to Object Oriented Programming and C++

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

C++ Important Questions with Answers

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

Introduction to Programming

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Constructors for classes

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

More on Objects in JAVA TM

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

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

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

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

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

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

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

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

Reusability. Relationships among Objects. Relationships among Objects

COMP 110/L Lecture 20. Kyle Dewey

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

C10: Garbage Collection and Constructors

Introduction to Object-Oriented Programming

C++ Inheritance and Encapsulation

Inheritance. Chapter 15 & additional topics

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

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

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

Virtual functions concepts

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

GEA 2017, Week 4. February 21, 2017

Bounding Object Instantiations, Part 2

Inheritance and Polymorphism. CS180 Fall 2007

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

OVERRIDING. 7/11/2015 Budditha Hettige 82

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers

Object Oriented Software Design II

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

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

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

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

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

Object Oriented Software Design II

Programming II (CS300)

Midterm Review. PIC 10B Spring 2018

CSE 333 Lecture 9 - intro to C++

EMBEDDED SYSTEMS PROGRAMMING OO Basics

Inheritance and object compatibility

CS 251 Intermediate Programming Inheritance

Polymorphism Part 1 1

Inheritance. A mechanism for specialization A mechanism for reuse. Fundamental to supporting polymorphism

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

8. Object-oriented Programming. June 15, 2010

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Overriding Variables: Shadowing

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

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

Making Inheritance Work: C++ Issues

Overview of the lecture. Some key issues in programming Java programming. CMPT Data and Program Abstraction. Some of the key programming issues

Making Inheritance Work: C++ Issues

Introduction to C++ Part II. Søren Debois. Department of Theoretical Computer Science IT University of Copenhagen. September 12th, 2005

Extending Classes (contd.) (Chapter 15) Questions:

04-24/26 Discussion Notes

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

Polymorphism. return a.doublevalue() + b.doublevalue();

Inheritance -- Introduction

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Classes, Objects, and OOP in Java. June 16, 2017

Main Topics. Study Tactics. Exam Structure, Roughly. Java Fundamentals. CISC 3120 Midterm Review Guide

INHERITANCE AND EXTENDING CLASSES

Inheritance and Polymorphism

Lecture 15: Object-Oriented Programming

What does it mean by information hiding? What are the advantages of it? {5 Marks}

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Java for Non Majors Spring 2018

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

CSSE 220. Interfaces and Polymorphism. Check out Interfaces from SVN

Transcription:

Critique this Code string const & findsmallest(vector<string> const &v) string smallest = v[0]; for (unsigned int i = 0; i < v.size(); i++) if (v[i] < smallest) smallest = v[i]; return smallest; Hint: It will crash badly! (Next slide please ) 1

Is this better? string const & findsmallest(vector<string> const &v) string const & smallest = v[0]; for (unsigned int i = 0; i < v.size(); i++) if (v[i] < smallest) smallest = v[i]; return smallest; Hint: Now it won t compile! (Next slide please ) 2

Without const? string const & findsmallest(vector<string> const &v) string const & smallest = v[0]; for (unsigned int i = 0; i < v.size(); i++) if (v[i] < smallest) smallest = v[i]; return smallest; Hint: Try running this! (Next slide please ) 3

How about this? string const & findsmallest(vector<string> const &v) string const * smallest = &v[0]; for (unsigned int i = 0; i < v.size(); i++) if (v[i] < *smallest) smallest = &v[i]; return *smallest; (Next slide please ) 4

Another approach. How should we call it? string const & findsmallest(vector<string> const &v) int smallestindex = 0; for (unsigned int i = 0; i < v.size(); i++) if (v[i] < v[smallestindex]) smallestindex = i; return v[smallestindex]; How should we call it? string s = findsmallest( ); string &s = findsmallest( ); string const &s = findsmallest( ); 5

Inheritance: Java vs. C++ Many aspects in C++ similar to Java, but many differences also. Let s start with the Lingo: Java C++ super class base class subclass derived class 6

Base Class Syntax: Java vs. C++ public class Animal private int size, age; Java public Animal(int s, int a) size = s; age = a; public void print() System.out.print( S: + size +, A: + age); class Animal private: int size, age; C++ public: Animal(int s, int a) : size(s), age(a) void print() cout << S: << size << A: << age; ; 7

Derived Class Syntax: Java vs. C++ Java public class Cat extends Animal private int whiskers; public Cat(int s, int a, int w) super(s, a); whiskers = w; public void print() super.print(); System.out.print(, W: + whiskers); class Cat : public Animal private: int whiskers; C++ public: Cat(int s, int a, int w) : Animal(s, a), whiskers(w) ; void print() Animal::print(); cout <<,W: << whiskers; 8

Slicing: Java vs. C++ Java Cat c = new Cat(8, 4, 200); Cat c(8, 4, 200); C++ Animal a = c; a and c are references to the same object, which is class Cat c views the object as type Cat; a views it as type Animal Animal a = c; OR Animal a; a = c; // Copy constructor // Assignment a and c are separate objects. A is an Animal; c is a Cat. a retains a slice of c. Are we doomed? Not completely: Animal &a = c; // More like Java Unfortunately, slicing does ruin some things as we ll see later. 9

Binding : Java vs. C++ Java Cat c = new Cat(8, 4, 100); Animal a = c; a.print(); Output is: S: 8, A: 4, W: 100 Late Binding or Dynamic Dispatch Advantage: Usually what we want C++ Cat c(8, 4, 100); Animal &a = c; a.print(); Output: S: 8, A: 4 Early Binding or Static Dispatch Advantage: Slightly more efficient Can we force these languages to do the opposite if we want to? (Next slide please ) 10

Forcing Early/Late Binding: Java vs. C++ Can we force these languages to do the opposite if we want to? Yes, but in both cases this requires a modification to the base/super class! To force early binding in Java: In the superclass declare the method as final. (But then it cannot be over-ridden!) To force late binding in C++: In the base class declare the function as virtual. It will now be considered virtual in all descendents, not just the immediately derived class. Rule of thumb for C++: If a function might be over-ridden one day, declare it as virtual. 11

Bad News C++ can do dynamic binding, so why is Java favored so heavily for inheritance? Java: ArrayList<Animal> list = new ArrayList<Animal>(); list.add(new Cat()); list.add(new Dog()); list.add(new Ostrich()); for (Animal a : list) a.print(); C++: Try same thing with a vector<animal>. Assume print is declared virtual. Will we reap the benefits of dynamic dispatch? (Hint: C++ collections store copies.) // dynamic dispatch 12

Another Example, but not as Bad void f(animal x) x.print(); f(cat()); f(dog()); f(ostrich()); This can be corrected easily. How? 13

Polymorphism: The Bottom Line To use polymorphism effectively in C++: You need to ensure the base class is anticipating it (by use of virtual). You may need to use pointers for collections. 14

Subtle Problem! Cat *p = new Cat(8, 4, 200); Animal *q = p; delete q; What will happen? (Next slide please ) 15

Subtle Problem! Cat *p = new Cat(8, 4, 200); Animal *q = p; delete q; Static dispatch! It runs the Animal destructor. Only part of the object is destroyed. Memory leak! Rule of thumb for destructors: If there is any chance that your class may be extended one day, declare the destructor as virtual! 16

Inheritance: Copy Constructor and Assignment Default copy constructor: Calls copy constructor for base class Calls copy constructor for all members Default operator=: Calls operator= for base class Calls operator= for all members Normally this is fine, but what if you need to write your own? (Next slide please ) 17

Inheritance: Copy Constructor and Assignment When implementing these in a derived class, don t forget to explicitly invoke the base versions! Cat(Cat const &other) : Animal(other), whiskers(other.whiskers) Cat & operator=(cat const &rhs) if (this!= &rhs) Animal::operator=(rhs); whiskers = rhs.whiskers; return *this; 18

Abstract: Java vs. C++ Java allows abstract methods and classes: An abstract method does not have an implementation (subclasses will implement it.) abstract void foo(); A class with an abstract method must be an abstract class. public abstract class bar An abstract class cannot be instantiated. Abstract methods/classes are rarely used in Java; interfaces are favored. C++: Abstract function must be virtual and end with = 0. What the??? virtual void foo() = 0; // completely bizarre A class with an abstract function is automatically abstract. An abstract class cannot be instantiated. Used frequently in places where Java would use an interface. 19

Inheritance Casting Animal *p = new Cat(8, 4, 100); p->whiskers // doesn t compile Java-style casting is allowed: ((Cat *) p)->whiskers // works, but Will not throw exceptions for illegal casts! Favor this: (dynamic_cast<cat *>(p))->whiskers (Throws exceptions for illegal casts.) 20