1 CSE 303 Lecture 24 Inheritance in C++, continued slides created by Marty Stepp

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
CSE341: Programming Languages Lecture 22 Multiple Inheritance, Interfaces, Mixins Dan Grossman Fall 2011.
Polymorphism, Virtual Methods and Abstract Classes.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 CSE 303 Lecture 23 Inheritance in C++ slides created by Marty Stepp
Operator Overloading: indexing Useful to create range-checked structures: class four_vect { double stor[4]; // private member, actual contents of vector.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
Inheritance and Polymorphism CS351 – Programming Paradigms.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
OOP Languages: Java vs C++
Inheritance using Java
Programming Languages and Paradigms Object-Oriented Programming.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
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
- 1 - C++ Inheritance Data Abstraction and Abstract Data Types – Abstract Data Type Encapsulated data type Accessible only through interface Properties.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
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.
Programming Languages and Paradigms Object-Oriented Programming.
CS212: Object Oriented Analysis and Design Lecture 15: Inheritance in C++ -II.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance Revisited Other Issues. Multiple Inheritance Also called combination--not permitted in Java, but is used in C++ Also called combination--not.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
CS212: Object Oriented Analysis and Design Lecture 16: Runtime Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
C++ General Characteristics: - Mixed typing system - Constructors and destructors - Elaborate access controls to class entities.
OOP, Inheritance and Polymorphism Lecture 6. Object relations  Inheritance is ‘a kind of’, ‘a type of’ e.g. a revolver is a type of gun  Aggregation.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Virtual Function and Polymorphism
7. Inheritance and Polymorphism
Polymorphism, Abstract Classes & Interfaces
Object-Oriented Programming
A tree set Our SearchTree class is essentially a set.
Inheritance, Polymorphism and the Object Memory Model
Interfaces and Inheritance
Object Oriented Analysis and Design
Extending Classes.
Java Programming Language
Virtual Functions Department of CSE, BUET Chapter 10.
A tree set Our SearchTree class is essentially a set.
Polymorphism, Abstract Classes & Interfaces
CSE 303 Concepts and Tools for Software Development
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Fundaments of Game Design
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Chapter 8: Class Relationships
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Overview of C++ Polymorphism
C++ Inheritance I CSE 333 Autumn 2018
C++ Inheritance I CSE 333 Winter 2019
Lecture 10 Concepts of Programming Languages
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

1 CSE 303 Lecture 24 Inheritance in C++, continued slides created by Marty Stepp

2 Recall: Investments design we implemented the inheritance between Stock and DividendStock now we'd like an interface for the top-level supertype

3 Interfaces, abstract classes Java provides two special features for creating type hierarchies:  interfaces: Sets of method declarations with no bodies. Classes can promise to implement an interface. Provides a supertype without any code sharing. key benefit: polymorphism. Can treat multiple types the same way.  abstract classes: Partially implemented classes that can have a mixture of declarations (without bodies) and definitions (with bodies). a hybrid between a class and an interface C++ does not have interfaces, but it (sort of) has abstract classes.

4 Pure virtual methods class Name { public: virtual returntype name(parameters) = 0;... }; pure virtual method: One that is declared but not implemented.  If a class has any pure virtual methods, no objects of it can be made. We call this an abstract class.  declared by setting the method equal to 0  must be implemented by subclasses (else they will be abstract)

5 An "interface" #ifndef _ASSET_H #define _ASSET_H // Represents assets held in an investor's portfolio. class Asset { public: virtual double cost() const = 0; virtual double marketValue() const = 0; virtual double profit() const = 0; }; #endif Simulate an interface using a class with all pure virtual methods  we don't need Asset.cpp, because no method bodies are written  other classes can extend Asset and implement the methods

6 Multiple inheritance class Name : public BaseClass1, public BaseClass2,..., public BaseClassN {... }; single inheritance: A class has exactly one superclass (Java) multiple inheritance: A class may have >= 1 superclass (C++)  powerful  helps us get around C++'s lack of interfaces (can extend many abstract classes if necessary)  can be confusing  often leads to conflicts or strange bugs

7 Potential problems common dangerous pattern: "The Diamond"  classes B and C extend A  class D extends A and B problems:  D inherits two copies of A's members  If B and C both define a member with the same name, they will conflict in D How can we solve these problems and disambiguate? D BC A

8 Disambiguating class B { // B.h public: virtual void method1(); }; class C { // C.h public: virtual void method1(); }; // D.cpp void D::foo() { method1(); // error - ambiguous reference to method1 B::method1(); // calls B's version } Explicit resolution is required to disambiguate the methods

9 Virtual base classes class Name : public virtual BaseClass1,..., public virtual BaseClassN {... }; declaring base classes as virtual eliminates the chance that a base class's members will be included twice

10 Friends (with benefits?) class Name { friend class Name;... }; a C++ class can specify another class or function as its friend  the friend is allowed full access to the class's private members!  a selective puncture in the encapsulation of the objects  (should not be used often) common usage: on overloaded operators outside a class ( e.g. << )

11 Private inheritance class Name : private BaseClass {... };  private inheritance: inherits behavior but doesn't tell anybody internally in your class, you can use the inherited behavior but client code cannot treat an object of your derived class as though it were an object of the base class (no polymorphism/subtype) a way of getting code reuse without subtyping/polymorphism

12 Objects in memory A* var1 = new B(); each object in memory consists of:  its fields, in declaration order  a pointer to a structure full of information about the object's methods (a virtual method table or vtable)  one vtable is shared by all objects of a class  the vtable also contains information about the type of the object use g++ -fdump-class-hierarchy to see memory layout field 3 field 2 field 1 __vptr method 1 method 3 method 2 type_info var

13 Object memory layout class A { int field1; virtual void m1(int x); virtual void m2(int x); virtual void m3(int x); }; class B : public A { float field2; virtual void m1(int x); }; class C : public B { int field3; virtual void m2(int x); }; int main() { C var1;... } var1 12A::m3() 8C::m2() 4B::m1() 0type_info 12field3 8field2 4field1 0__vptr vtable for class C

14 Multiple inheritance layout class A { int field1; virtual void m1(int x); virtual void m2(int x); }; class B { float field2; virtual void m3(int x); }; class C : public A, public B { int field3; virtual void m2(int x); virtual void m4(int x); }; int main() { C var1;... } var1 12C::m4() 8C::m2() 4A::m1() 0type_info 16field3 12field2 8__vptr2 4field1 0__vptr1 vtable1 for class C (A/C view) 4B::m3() 0type_info vtable2 for class C (B view)

15 Type-casting pointers Person* p1 = new Student(); Person* p2 = new Teacher(); Student* s1 = (Student*) p1; // ok Student* s2 = (Student*) p2; // subtle bugs!  casting up the inheritance tree works  but if the cast fails, can introduce subtle bugs  why is the above code a problem? p2 's vtable is the Teacher vtable; using it as a Student will cause the wrong methods to be called, or the wrong addresses to be mapped on lookups Person StudentTeacher

16 Dynamic (checked) casts Person* p1 = new Student(); Person* p2 = new Teacher(); Student* s1 = dynamic_cast (p1); // ok Student* s2 = dynamic_cast (p2); // s4 == NULL  dynamic_cast returns NULL if the cast fails  code still crashes, but at least it doesn't behave in unexpected ways Person StudentTeacher

17 Slicing class A {... }; class B : public A {... };... B var1; A var2 = var1; // sliced! slicing: When a derived object is converted into a base object.  extra info from B class is lost in var2  often, this is okay and doesn't cause any problems  but can lead to problems if data from the "A part" of var1 depends on data from the "B part" var2 16field4_B 12field3_B 8field2_A 4field1_A 0__vptr