CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.

Slides:



Advertisements
Similar presentations
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Advertisements

Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
CSE 374 Programming Concepts & Tools Hal Perkins Winter 2012 Lecture 19 – Introduction to C++
CSE341: Programming Languages Lecture 22 Multiple Inheritance, Interfaces, Mixins Dan Grossman Fall 2011.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
CSE341: Programming Languages Lecture 26 Subtyping for OOP Dan Grossman Fall 2011.
1 CSE 303 Lecture 23 Inheritance in C++ slides created by Marty Stepp
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
ISE 582: Web Technology for Industrial Engineers University of Southern California Department of Industrial and Systems Engineering Lecture 4 JAVA Cup.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
CSE 413 Programming Languages & Implementation Hal Perkins Autumn 2012 Ruby: Multiple Inheritance, Interfaces, Mixins 1.
Abstract classes and Interfaces. Abstract classes.
Inheritance using Java
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Polymorphism &Virtual Functions
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
TCP1201 OOPDS Lecture 4 1. Learning Objectives  To understand upcasting & downcasting  To understand static polymorphism and dynamic polymorphism 
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Object Oriented Software Development
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
Inheritance and Access Control CS 162 (Summer 2009)
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object-Oriented Programming Chapter Chapter
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Copyright © 2005 Elsevier Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Inheritance and Composition Reusing the code and functionality Unit - 04.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Interfaces, Mixins, & Multiple Inheritance CSE 413 Autumn 2008 Credit: Dan Grossman, CSE341, Sp08.
Overview of C++ Polymorphism
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
Variations on Inheritance Object-Oriented Programming Spring
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Inheritance in C++ Bryce Boe 2012/08/28 CS32, Summer 2012 B.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CSE 143 Lecture 13 Inheritance slides created by Ethan Apter
CSE 413 Programming Languages & Implementation Hal Perkins Autumn 2012 Multiple Inheritance, Interfaces, Mixins 1.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
CSE 374 Programming Concepts & Tools
7. Inheritance and Polymorphism
Inheritance and Polymorphism
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Polymorphism Lec
Java Programming Language
Virtual Functions Department of CSE, BUET Chapter 10.
Java – Inheritance.
Java Inheritance.
Overview of C++ Polymorphism
Inheritance and Polymorphism
Lecture 10 Concepts of Programming Languages
C++ Polymorphism Reference and pointer implicit type casting
Presentation transcript:

CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance

Subclassing In many ways, OOP is “all about” subclasses overriding methods –Often not what you want, but what makes OOP fundamentally different from, say, functional programming (Scheme, ML, Haskell, etc., cf. CSE413) C++ gives you lots more options than Java with different defaults, so it’s easy to scream “compiler bug” when you mean “I’m using the wrong feature”… 2

Subclassing in C++ Basic subclassing: class D : public C {... } This is public inheritance; C++ has other kinds too (won’t cover) –Differences affect visibility and issues when you have multiple superclasses (won’t cover) –So do not forget the public keyword 3

More on subclassing Not all classes have superclasses (unlike Java with Object) –(and classes can have multiple superclasses — more general and complexity-prone than Java) Terminology –Java (and others): “superclass” and “subclass” –C++ (and others): “base class” and “derived class” Our example code: House derives from Land which derives from Property (read the code, no time for detailed presentation) As in Java, can add fields/methods/constructors, and override methods 4

Constructor and destructors Constructor of base class gets called before constructor of derived class –Default (zero-arg) constructor unless you specify a different one after the : in the constructor –Initializer syntax: Foo::Foo(…): Bar(args); it(x) { … } Needed to execute superclass constructor with arguments; also works on instance variables and is preferred in production code (slogan: “initialization preferred over assignment”) Destructor of base class gets called after destructor of derived class So constructors/destructors really extend rather than override, since that is typically what you want –Java is the same 5

Method overriding, part 1 If a derived class defines a method with the same method name and argument types as one defined in the base class (perhaps because of an ancestor), it overrides (i.e., replaces) rather than extends If you want to use the base-class code, you specify the base class when making a method call ( class::method(…) ) –Like super in Java (no such keyword in C++ since there may be multiple inheritance) Warning: the title of this slide is part 1 6

Casting and subtyping An object of a derived class cannot be cast to an object of a base class. –For the same reason a struct T1 {int x,y,z;} cannot be cast to type struct T2 {int x,y;} (different size) A pointer to an object of a derived class can be cast to a pointer to an object of a base class. –For the same reason a struct T1* can be cast to type struct T2* (pointers to a location in memory) –(Story not so simple with multiple inheritance) After such an upcast, field-access works fine (prefix), but what do method calls mean in the presence of overriding? 7

An important example class A { public: void m1() { cout << "a1"; } virtual void m2() { cout << "a2"; } }; class B : public A { void m1() { cout << "b1"; } void m2() { cout << "b2"; } }; void f() { A* x = new B(); x->m1(); x->m2(); } 8

In words… A non-virtual method-call is resolved using the (compile-time) type of the receiver expression A virtual method-call is resolved using the (run-time) class of the receiver object (what the expression evaluates to) –Like in Java –Called “dynamic dispatch” A method-call is virtual if the method called is marked virtual or overrides a virtual method –So “one virtual” somewhere up the base-class chain is enough, but it’s probably better style to repeat it 9

More on two method-call rules For software-engineering, virtual and non-virtual each have advantages: –Non-virtual – can look at the code to know what you’re calling (even if subclass defines the same function) –Virtual – easier to extend code already written The implementations are the same and different: –Same: Methods just become functions with one extra argument this (pointer to receiver) –Different: Non-virtual: linker can plug in code pointer Virtual: At run-time, look up code pointer via “secret field” in the object 10

Destructors revisited class B : public A {... }... B * b = new B(); A * a = b; delete a; Will B::~B() get called (before A::~A() )? Only if A::~A() was declared virtual –Rule of thumb: Declare destructors virtual; usually what you want 11

Downcasts Old news: C pointer-casts: unchecked; better know what you are doing Java: checked; may raise ClassCastException (checks “secret field”) New news: C++ has “all the above” (several different kinds of casts) If you use single-inheritance and know what you are doing, the C-style casts (same pointer, assume more about what is pointed to) should work fine for downcasts Worth learning about the differences on your own 12

Pure virtual methods A C++ “pure virtual” method is like a Java “abstract” method. Some subclass must override because there is no definition in base class Makes sense with dynamic dispatch Unlike Java, no need/way to mark the class specially Funny syntax in base class; override as usual: class C { virtual t0 m(t1,t2,...,tn) = 0;... }; Side-comment: with multiple inheritance and pure-virtual methods, no need for a separate notion of Java-style interfaces 13

C++ summary Lots of new syntax and gotchas, but just a few new concepts: –Objects vs. pointers to objects –Destructors –virtual vs. non-virtual –pass-by-reference –Plus all the stuff we didn’t get to, especially templates, exceptions, and operator overloading. –Later (if time): why objects are better than code- pointers – coding up object-like idioms in C 14