C++ Inheritance II, Casting

Similar documents
C++ Inheritance II, Casting

C++ Inheritance I. CSE 333 Spring Instructor: Justin Hsia

CSE 333 Lecture 15 - inheritance

CSE 333 Lecture 15 - inheritance

CSE 333 Lecture C++ final details, networks

C++ Constructor Insanity

C++ Inheritance I. CSE 333 Autumn 2018

Memory and Arrays. CSE 333 Spring Instructor: Justin Hsia

Server-side Programming

Concurrency and Threads

C++ Programming: Polymorphism

ECE 3574: Dynamic Polymorphism using Inheritance

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

OBJECT ORIENTED PROGRAMMING USING C++

C++ Constructor Insanity

CS3157: Advanced Programming. Outline

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

CS11 Advanced C++ Fall Lecture 7

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

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

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Where do we stand on inheritance?

Inheritance, Polymorphism and the Object Memory Model

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

C++ Class Details, Heap

IP Addresses, DNS. CSE 333 Spring Instructor: Justin Hsia

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

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

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

W3101: Programming Languages C++ Ramana Isukapalli

Common Misunderstandings from Exam 1 Material

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

C++ Modern and Lucid C++ for Professional Programmers

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

G52CPP C++ Programming Lecture 13

C++ Important Questions with Answers

The Heap and Structs. CSE 333 Spring Instructor: Justin Hsia

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

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

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

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

Object Oriented Software Design II

Object Oriented Software Design II

CPSC 427: Object-Oriented Programming

C++ for Java Programmers

04-24/26 Discussion Notes

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

C++ (classes) Hwansoo Han

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Memory, Data, & Addressing II

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

Vector and Free Store (Pointers and Memory Allocation)

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

CSE 303 Lecture 23. Inheritance in C++ slides created by Marty Stepp

Polymorphism Part 1 1

CPSC 427: Object-Oriented Programming

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

Data Abstraction. Hwansoo Han

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

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

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

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

Tokens, Expressions and Control Structures

Polymorphism. Zimmer CSCI 330

Lecture 15a Persistent Memory & Shared Pointers

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

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

Chapter 15. Object-Oriented Programming

CPSC 427: Object-Oriented Programming

Object-Oriented Programming for Scientific Computing

G52CPP C++ Programming Lecture 20

Chapter 17 vector and Free Store. Bjarne Stroustrup

CSE 431S Type Checking. Washington University Spring 2013

15: Polymorphism & Virtual Functions

Chapter 17 vector and Free Store

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Object-Oriented Principles and Practice / C++

Do not turn the page until 12:30.

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Chapter 14 Abstract Classes and Interfaces

Inheritance and Polymorphism

Dr. Md. Humayun Kabir CSE Department, BUET

CSE 333 Lecture smart pointers

CS250 Final Review Questions

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Short Notes of CS201

G52CPP C++ Programming Lecture 12

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Lecture 2, September 4

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

C++ Templates. CSE 333 Autumn 2018

CS201 - Introduction to Programming Glossary By

Inheritance & Polymorphism. Object-Oriented Programming Spring 2015

G Programming Languages - Fall 2012

Inheritance, and Polymorphism.

VIRTUAL FUNCTIONS Chapter 10

Inheritance and Polymorphism

Programming, numerics and optimization

COMP322 - Introduction to C++

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Transcription:

C++ Inheritance II, Casting CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon Huang Wei Lin

Administrivia Exercise 14 released today, due Friday C++ inheritance with abstract class hw3 is due next Thursday (5/17) Section tomorrow will also help you get started Midterm grading Submit regrade requests via Gradescope for each subquestion These go to different graders Regrade requests open until end of tomorrow (5/10) Exam will be curved up (free points for everyone!) 2

Lecture Outline C++ Inheritance Static Dispatch Abstract Classes Constructors and Destructors Assignment C++ Casting Reference: C++ Primer, Chapter 15 3

virtual is sticky If X::f() is declared virtual, then a vtable will be created for class X and for all of its subclasses The vtables will include function pointers for (the correct) f f() will be called using dynamic dispatch even if overridden in a derived class without the virtual keyword Good style to help the reader by using override and virtual in derived classes 4

Static (Non-Virtual) Dispatch By default, methods are dispatched statically At compile time, the compiler writes in a call to the address of the class method in the.text segment Based on the compile-time visible type of the callee This is different than Java class Derived : public Base {... int main(int argc, char** argv) { Derived d; Derived* dp = &d; Base* bp = &d; dp->foo(); bp->foo(); return 0; Derived::foo() add $0x1d, %eax... Base::foo() add $0x1b, %eax... 5

Static Dispatch Example Removed virtual on methods: double Stock::GetMarketValue() const; double Stock::GetProfit() const; Stock.h DividendStock dividend(); DividendStock* ds = &dividend; Stock* s = &dividend; // Invokes DividendStock::GetMarketValue() ds->getmarketvalue(); // Invokes Stock::GetMarketValue() s->getmarketvalue(); // invokes Stock::GetProfit(), since that method is inherited. // Stock::GetProfit() invokes Stock::GetMarketValue(). ds->getprofit(); // invokes Stock::GetProfit(). // Stock::GetProfit() invokes Stock::GetMarketValue(). s->getprofit(); 6

Why Not Always Use virtual? Two (fairly uncommon) reasons: Efficiency: Non-virtual function calls are a tiny bit faster (no indirect lookup) A class with no virtual functions has objects without a vptr field Control: If f() calls g() in class X and g is not virtual, we re guaranteed to call X::g() and not g() in some subclass Particularly useful for framework design In Java, all methods are virtual, except static class methods, which aren t associated with objects In C++ and C#, you can pick what you want Omitting virtual can cause obscure bugs 7

Mixed Dispatch Example mixed.cc class A { // m1 will use static dispatch void m1() { cout << "a1, "; // m2 will use dynamic dispatch virtual void m2() { cout << "a2"; void main(int argc, char** argv) { A a; B b; A* a_ptr_a = &a; A* a_ptr_b = &b; B* b_ptr_a = &a; B* b_ptr_b = &b; class B : public A { void m1() { cout << "b1, "; // m2 is still virtual by default void m2() { cout << "b2"; a_ptr_a->m1(); // a_ptr_a->m2(); // a_ptr_b->m1(); // a_ptr_b->m2(); // b_ptr_b->m1(); // b_ptr_b->m2(); // 8

Peer Instruction Question Whose Foo() is called? Vote at http://pollev.com/justinh class A { void Foo(); test.cc Q1 Q2 A. A A B. A B C. D A D. D B E. We re lost void Bar() { D d; E e; A* a_ptr = &d; C* c_ptr = &e; // Q1: a_ptr->foo(); // Q2: c_ptr->foo(); class B : public A { virtual void Foo(); class C : public B { class D : public C { void Foo(); class E : public C { 9

Abstract Classes Sometimes we want to include a function in a class but only implement it in derived classes In Java, we would use an abstract method In C++, we use a pure virtual function Example: virtual string noise() = 0; A class containing any pure virtual methods is abstract You can t create instances of an abstract class Extend abstract classes and override methods to use them A class containing only pure virtual methods is the same as a Java interface Pure type specification without implementations 10

Lecture Outline C++ Inheritance Static Dispatch Abstract Classes Constructors and Destructors Assignment C++ Casting Reference: C++ Primer, Chapter 15 11

Derived-Class Objects A derived object contains subobjects corresponding to the data members inherited from each base class No guarantees about how these are laid out in memory (not even contiguousness between subobjects) Conceptual structure of DividendStock object: members inherited from Stock members defined by DividendStock symbol_ total_shares_ total_cost_ current_price_ dividends_ 12

Constructors and Inheritance A derived class does not inherit the base class constructor The derived class must have its own constructor The synthesized default constructor will initialize the derived class non- plain ol data member variables to zero-equivalents and invokes the default constructor of the base class Compiler error if the base class has no default constructor The base class constructor is invoked before the constructor of the derived class You can use the initialization list of the derived class to specify which base class constructor to use 13

Constructor Examples class Base { // no default ctor Base(int y) : y(y) { int y; // Compiler error when you try to // instantiate a Der1, as the // synthesized default ctor needs // to invoke Base's default ctor. class Der1 : public Base { int z; class Der2 : public Base { Der2(int y, int z) : Base(y), z(z) { int z; badctor.cc // has default ctor class Base { int y; goodctor.cc // works now class Der1 : public Base { int z; // still works class Der2 : public Base { Der2(int z) : z(z) { int z; 14

Destructors and Inheritance Destructor of a derived class: First runs body of the dtor Then invokes of the dtor of the base class Static dispatch of destructors is almost always a mistake! Good habit to always define a dtor as virtual Empty body if there s no work to do class Base { Base() { x = new int; ~Base() { delete x; int* x; class Der1 : public Base { Der1() { y = new int; ~Der1() { delete y; int* y; void foo() { Base* b0ptr = new Base; Base* b1ptr = new Der1; baddtor.cc delete b0ptr; // OK delete b1ptr; // leaks Der1::y 15

Assignment and Inheritance C++ allows you to assign the value of a derived class to an instance of a base class class Base { Base(int x) : x(x) { int x; slicing.cc Known as object slicing class Der1 : public Base { Der1(int y) : Base(16), y(y) { int y; void foo() { Base b(1); Der1 d(2); d = b; // b = d; // 16

STL and Inheritance Recall: STL containers store copies of values What happens when we want to store mixes of object types in a single container? (e.g. Stock and DividendStock) You get sliced #include <list> #include "Stock.h" #include "DividendStock.h" int main(int argc, char** argv) { Stock s; DividendStock ds; list<stock> li; li.push_back(s); // OK li.push_back(ds); // OUCH! return 0; 17

STL and Inheritance Instead, store pointers to heap-allocated objects in STL containers No slicing! sort() does the wrong thing You have to remember to delete your objects before destroying the container Smart pointers! 18

Lecture Outline C++ Inheritance Static Dispatch Abstract Classes Constructors and Destructors Assignment C++ Casting Reference: C++ Primer 4.11.3, 19.2.1 19

Explicit Casting in C Simple syntax: lhs = (new_type) rhs; Used to: Convert between pointers of arbitrary type Don t change the data, but treat differently Forcibly convert a primitive type to another Actually changes the representation You can still use C-style casting in C++, but sometimes the intent is not clear 20

Casting in C++ C++ provides an alternative casting style that is more informative: static_cast<to_type>(expression) dynamic_cast<to_type>(expression) const_cast<to_type>(expression) reinterpret_cast<to_type>(expression) Always use these in C++ code Intent is clearer Easier to find in code via searching 21

static_cast L19: C++ Inheritance II, Casting static_cast can convert: class A { int x; staticcast.cc Pointers to classes of related type Compiler error if classes are not related Dangerous to cast down a class hierarchy Non-pointer conversion e.g. float to int static_cast is checked at compile time void foo() { B b; C c; class B { float x; class C : public B { char x; // compiler error A* aptr = static_cast<a*>(&b); // OK B* bptr = static_cast<b*>(&c); // compiles, but dangerous C* cptr = static_cast<c*>(&b); 22

dynamic_cast L19: C++ Inheritance II, Casting dynamic_cast can convert: Pointers to classes of related type References to classes of related type dynamic_cast is checked at both compile time and run time Casts between unrelated classes fail at compile time Casts from base to derived fail at run time if the pointed-to object is not a full derived object void bar() { Base b; Der1 d; dynamiccast.cc class Base { virtual void foo() { float x; class Der1 : public Base { char x; // OK (run-time check passes) Base* bptr = dynamic_cast<base*>(&d); assert(bptr!= nullptr); // OK (run-time check passes) Der1* dptr = dynamic_cast<der1*>(bptr); assert(dptr!= nullptr); // Run-time check fails, returns nullptr bptr = &b; dptr = dynamic_cast<der1*>(bptr); assert(dptr!= nullptr); 23

const_cast const_cast adds or strips const-ness Dangerous (!) void foo(int* x) { *x++; void bar(const int* x) { foo(x); // compiler error foo(const_cast<int*>(x)); // succeeds int main(int argc, char** argv) { int x = 7; bar(&x); return 0; 24

reinterpret_cast reinterpret_cast casts between incompatible types Low-level reinterpretation of the bit pattern e.g. storing a pointer in an int, or vice-versa Works as long as the integral type is wide enough Converting between incompatible pointers Dangerous (!) This is used (carefully) in hw3 25

Implicit Conversion The compiler tries to infer some kinds of conversions When types are not equal and you don t specify an explicit cast, the compiler looks for an acceptable implicit conversion void bar(std::string x); void foo() { int x = 5.7; // conversion, float -> int bar("hi"); // conversion, (const char*) -> string char c = x; // conversion, int -> char 26

Sneaky Implicit Conversions (const char*) to string conversion? If a class has a constructor with a single parameter, the compiler will exploit it to perform implicit conversions At most, one user-defined implicit conversion will happen Can do int Foo, but not int Foo Baz class Foo { Foo(int x) : x(x) { int x; int Bar(Foo f) { return f.x; int main(int argc, char** argv) { return Bar(5); // equivalent to return Bar(Foo(5)); 27

Avoiding Sneaky Implicits Declare one-argument constructors as explicit if you want to disable them from being used as an implicit conversion path Usually a good idea class Foo { explicit Foo(int x) : x(x) { int x; int Bar(Foo f) { return f.x; int main(int argc, char** argv) { return Bar(5); // compiler error 28

Extra Exercise #1 Design a class hierarchy to represent shapes e.g. Circle, Triangle, Square Implement methods that: Construct shapes Move a shape (i.e. add (x,y) to the shape position) Returns the centroid of the shape Returns the area of the shape Print(), which prints out the details of a shape 29

Extra Exercise #2 Implement a program that uses Extra Exercise #1 (shapes class hierarchy): Constructs a vector of shapes Sorts the vector according to the area of the shape Prints out each member of the vector Notes: Avoid slicing! Make sure the sorting works properly! 30