Lecture 15: Even more pointer stuff Virtual function table

Similar documents
Lecture 14: more class, C++ streams

Lecture 13: more class, C++ memory management

Lecture 10: building large projects, beginning C++, C++ and structs

Lecture 20: templates

Short Notes of CS201

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

CS201 - Introduction to Programming Glossary By

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

G52CPP C++ Programming Lecture 13

Lecture 10: Potpourri: Enum / struct / union Advanced Unix #include function pointers

Lecture 8: Structs & File I/O

QUIZ Friends class Y;

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

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Simplest version of DayOfYear

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Lecture 2: Memory in C

Lecture 9: Potpourri: Call by reference vs call by value Enum / struct / union Advanced Unix

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

Pointers in C/C++ 1 Memory Addresses 2

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

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

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

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

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

QUIZ. What are 3 differences between C and C++ const variables?

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

C++ (Non for C Programmer) (BT307) 40 Hours

Object-Oriented Programming

Lecture 2, September 4

Inheritance, Polymorphism and the Object Memory Model

G52CPP C++ Programming Lecture 10. Dr Jason Atkin

COMP-520 GoLite Tutorial

Lecture 4: Build Systems, Tar, Character Strings

step is to see how C++ implements type polymorphism, and this Exploration starts you on that journey.

CSE 303: Concepts and Tools for Software Development

CSE351 Winter 2016, Final Examination March 16, 2016

A brief introduction to C++

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

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

CS201 Some Important Definitions

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

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

EECS 211 Lab 7. Raw Pointers and Memory Management Winter Getting the code. Basic Raw Pointer Syntax. De-referencing

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

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

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Midterm Exam #2 Review. CS 2308 :: Spring 2016 Molly O'Neil

Interview Questions of C++

CS61C : Machine Structures

Heap Arrays and Linked Lists. Steven R. Bagley

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

Lesson Plan. Subject: OBJECT ORIENTED PROGRAMMING USING C++ :15 weeks (From January, 2018 to April,2018)

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Lecture 7: file I/O, more Unix

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Cpt S 122 Data Structures. Introduction to C++ Part II

CIS 190: C/C++ Programming. Lecture 11 Polymorphism

QUIZ. Source:

Lecture 18 Tao Wang 1

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

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

G52CPP C++ Programming Lecture 20

Lecture 4: Memory Management & The Programming Interface

CS 61c: Great Ideas in Computer Architecture

Part X. Advanced C ++

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

COMP 2355 Introduction to Systems Programming

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Data Abstraction. Hwansoo Han

Software Engineering /48

For example, let s say we define an array of char of size six:

2 ADT Programming User-defined abstract data types

Ch. 11: References & the Copy-Constructor. - continued -

CS61C : Machine Structures

Programming, numerics and optimization

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Programming for Engineers in Python

Data Structures (list, dictionary, tuples, sets, strings)

A heap, a stack, a bottle and a rack. Johan Montelius HT2017

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

Syllabus of C++ Software for Hands-on Learning: This course offers the following modules: Module 1: Getting Started with C++ Programming

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

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

CS 360: Programming Languages Lecture 12: More Haskell

CS24 Week 3 Lecture 1

Chapter 10 Introduction to Classes

Memory management COSC346

Inheritance and Interfaces

In Java we have the keyword null, which is the value of an uninitialized reference type

COEN244: Class & function templates

内存管理. Memory management

Lecture Topics. Administrivia

C++ Important Questions with Answers

COP Programming Assignment #7

Page 1. Stuff. Last Time. Today. Safety-Critical Systems MISRA-C. Terminology. Interrupts Inline assembly Intrinsics

Transcription:

CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 15: Even more pointer stuff Virtual function table May 16 th, 2018 Hank Childs, University of Oregon

Any 3C, 3D questions?

PNMreader::PNMreader(char *f)

Project 3E You will need to think about how to accomplish the data flow execution pattern and think about how to extend your implementation to make it work. This prompt is vaguer than some previous ones not all of the details are there on how to do it

Project 3E

Project 3E Worth 3% of your grade Assigned today, due May 23

Example of data flow (image processing) FileReader Crop Transpose Invert Color Concatenate FileWriter

Make it easy on yourself to run

Other ways to make life easier tab from shell: auto-completes Ctrl-R: searches backwards in your shell history

More on Pointers

Safe deposit box (Poor) Analogy

(Poor) Analogy You go to the bank You ask for a safe deposit box The key to the box is a pointer You get access to a space in the vault The box in the vault is the memory on the heap

Analogy Continued You go to teller and request a safe deposit box Teller gives you a key, to box #105 Then you go back the next day and request another safe deposit box, to box #107 And you throw out the key to box #105 and only keep the key to box #107 This is a memory leak No one will ever be able to access to box #105

Now let s think about stack/heap Code Data Stack Location Value buffer 0x7fff0 0x10000 Free 0x103E8 0x103E8 [100] vals 0x10000 [1000] vals Heap

Analogy Continued You go to teller and request a safe deposit box Teller gives you a key, to box #105 (buffer) You make a copy of the key for your friend (buffer2) Now you and your friend have access to box #105 If your friend changes the contents, then it affects you Terminology: this is called a shallow copy

Now let s think about stack/heap Code Data buffer buffer2 Stack Location Value 0x7fff0 0x10000 0x7ffec 0x10000 Free 0x10000 [1000] vals Heap

Analogy Continued (But Starting to Break Down) You go to teller and request a safe deposit box Teller gives you a key, to box #105 (buffer) You fill the box You later request a second safe deposit box Teller gives you a key, to box #107 (buffer2) You examine box #105. Whatever is in 105, you put in 107 Example: $10K in 105. So put an additional $10K in 107. ($20K total) This is called a deep copy

Now let s think about stack/heap Code Data buffer buffer2 Stack Location Value 0x7fff0 0x10000 0x7ffec 0x103E8 Free 0x103E8 [1000] vals 0x10000 [1000] vals Heap

Arrays on the stack are different Code Data You cannot re-assign A to another value. A is bound to its stack location But you can assign a pointer to point at A s location. And compiler can do this automatically (int *A_ptr = A;) Stack Location Value A 0x7fff0 0.5 0x7ffec 1.5 0x7ffe8 2.5 Free Heap

Default Methods C++ makes 4 methods for you by default: Default constructor Copy constructor Assignment operator Destructor

What if there are data members?

For Image THIS WILL CRASH

Solution This will prevent you from accidentally calling copy constructor or assignment operator (You should add this to your Image class)

And you may be using assignment operators right now without knowing it so = is doing more work than you might expect

Inline function inlined functions: hint to a compiler that can improve performance basic idea: don t actually make this be a separate function that is called Instead, just pull the code out of it and place it inside the current function new keyword: inline The compiler sometimes refuses your inline request (when it thinks inliningwon t improve performance), but it does it silently.

Inlines can be automatically done within class definitions Even though you don t declare this as inline, the compiler treats it as an inline

You should only do inlines within header files int Doubler(int X); Left: function is inlined in every.c that includes it no problem Right: function is defined in every.c that includes it duplicate symbols

New Content

How C++ Does Methods

this : pointer to current object From within any struct s method, you can refer to the current object using this

How methods work under the covers (1/4)

How methods work under the covers (2/4) Addr. Variable Value 0x8000 MIC/myI nt 12 Addr. Variable Value 0x8000 MIC/myI nt 12 0x8004 mic 0x8000

How methods work under the covers (3/4)

How methods work under the covers (4/4) The compiler secretly slips this onto the stack whenever you make a method call. It also automatically changes myint to this->myint in methods. Addr. Variable Value 0x8000 MIC/myI nt 12 Addr. Variable Value 0x8000 MIC/myI nt 12 0x8004 mic 0x8000 Addr. Variable Value 0x8000 MIC/myI nt 13 0x8004 this 0x8000

Virtual Function Tables

Virtual functions Virtual function: function defined in the base type, but can be re-defined in derived type. When you call a virtual function, you get the version defined by the derived type

Virtual functions: example

Picking the right virtual function It seems like the compiler should be able to figure this out... it knows that a is of type A and it knows that b is of type B??????

Picking the right virtual function?????? So how to does the compiler know? How does it get B for b and A for a?

Virtual Function Table Let C be a class and X be an instance of C. Let C have 3 virtual functions & 4 non-virtual functions C has a hidden data member called the virtual function table This table has 3 rows Each row has the correct definition of the virtual function to call for a C. When you call a virtual function, this table is consulted to locate the correct definition.

what will this print? Showing the existence of the virtual function pointer with sizeof() empty objects have size of 1? why?!? Answer: so every object has a unique address.

Virtual Function Table Let C be a class and X be an instance of C. Let C have 3 virtual functions & 4 non-virtual functions Let D be a class that inherits from C and Y be an instance of D. Let D add a new virtual function D s virtual function table has 4 rows Each row has the correct definition of the virtual function to call for a D.

More notes on virtual function tables There is one instance of a virtual function table for each class Each instance of a class shares the same virtual function table Easy to overwrite (i.e., with a memory error) And then all your virtual function calls will be corrupted Don t do this! ;)

Virtual function table: example

Virtual function table: example

Questions What does the virtual function table look like for a Shape? What does Shape s virtual function table look like? Trick question: Shape can t be instantiated, precisely because you can t make a virtual function table abstract type due to pure virtual functions

Questions What is the virtual function table for Rectangle? (this is a code fragment from my 2C solution)

Calling a virtual function Let X be an instance of class C. Assume you want to call the 4 th virtual function Let the arguments to the virtual function be an integer Y and a float Z. Then call: (X.vptr[3])(&X, Y, Z); The 4 th virtual function has index 3 (0-indexing) The pointer to the virtual function pointer (often called a vptr) is a data member of X Secretly pass this as first argument to method

Inheritance and Virtual Function Tables A Foo1 This whole scheme gets much harder with multiple B inheritance, and you have to carry around multiple Foo1 virtual function tables. Foo2 Location of Foo1 Location of Foo1 Location of Foo2 : public B Same as B s This is how you can treat a C as a B C Foo1 Foo2 Location of Foo1 Location of Foo2 Foo3 Location of Foo3

Virtual Function Table: Summary Virtual functions require machinery to ensure the correct form of a virtual function is called This is implemented through a virtual function table Every instance of a class that has virtual functions has a pointer to its class s virtual function table The virtual function is called via following pointers Performance issue

Now show Project 2D in C++ Comment: C/C++ great because of performance Performance partially comes because of a philosophy of not adding magic to make programmer s life easier C has very little pixie dust sprinkled in Exception: \0 to terminate strings C++ has more Hopefully this will demystify one of those things (virtual functions)

vptr.c

Pitfalls

Pitfall #1 This is using call-by-value, not call-by-reference.

Pitfall #2

Pitfall #3 int *s = new int[6*sizeof(int)];

Pitfall #4 Assume: int *X = new int[100]; What is sizeof(x)? What is sizeof(*x)?

Pitfall #5

(not-a-)pitfall #6 Top requires memory allocation / deletion, and does extra copy.

Pitfall #7 For objects on the stack, the destructors are called when a function goes out of scope You may have a perfectly good function, but it segfaults on return Especially tricky for main program ran to completion, and crashed at the very end

Pitfall #8

Bonus Topics

Backgrounding & : tell shell to run a job in the background Background means that the shell acts as normal, but the command you invoke is running at the same time. sleep 60 vs sleep 60 & When would backgrounding be useful?

Suspending Jobs You can suspend a job that is running Press Ctrl-Z The OS will then stop job from running and not schedule it to run. You can then: make the job run in the background. Type bg make the job run in the foreground. Type fg like you never suspended it at all!!

Web pages ssh l <user name> ix.cs.uoregon.edu cd public_html put something in index.html à it will show up as http://ix.cs.uoregon.edu/~<username>

Web pages You can also exchange files this way scp file.pdf <username>@ix.cs.uoregon.edu:~/public_html point people to http://ix.cs.uoregon.edu/~<username>/file.pdf Note that ~/public_html/dir1 shows up as http://ix.cs.uoregon.edu/~<username>/dir1 ( ~/dir1 is not accessible via web)