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

Similar documents
Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer?

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

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. Can you find 5 errors in this code?

Ch. 12: Operator Overloading

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

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

Computer Systems Lecture 9

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

QUIZ Friends class Y;

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

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++ for Java Programmers

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

Lecture 13: more class, C++ memory management

QUIZ. Source:

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

CS201 Some Important Definitions

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Lecture 5. Announcements: Today: Finish up functions in MIPS

CS201 Latest Solved MCQs

Computer Architecture Prof. Mainak Chaudhuri Department of Computer Science & Engineering Indian Institute of Technology, Kanpur

Functions in MIPS. Functions in MIPS 1

CPS311 Lecture: Procedures Last revised 9/9/13. Objectives:

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

Ch. 10: Name Control

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Lectures 5. Announcements: Today: Oops in Strings/pointers (example from last time) Functions in MIPS

Homework #2 Think in C, Write in Assembly

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Object-Oriented Principles and Practice / C++

Lecture 14: more class, C++ streams

Written by John Bell for CS 342, Spring 2018

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

This wouldn t work without the previous declaration of X. This wouldn t work without the previous declaration of y

Run Time Environment

Object-Oriented Principles and Practice / C++

Course Administration

Assembly labs start this week. Don t forget to submit your code at the end of your lab section. Download MARS4_5.jar to your lab PC or laptop.

CSE 401 Final Exam. December 16, 2010

SYSTEM CALL IMPLEMENTATION. CS124 Operating Systems Fall , Lecture 14

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Object-Oriented Programming, Iouliia Skliarova

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

CA31-1K DIS. Pointers. TA: You Lu

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Principles and Practice / C++

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008

Ch. 3: The C in C++ - Continued -

Exercise 6.2 A generic container class

Operator Overloading in C++ Systems Programming

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

BLM2031 Structured Programming. Zeyneb KURT

Homework #3 CS2255 Fall 2012

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

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

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Chapter 1 Getting Started

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

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

Pointers Ch 9, 11.3 & 13.1

G Programming Languages - Fall 2012

CSE 333 Midterm Exam July 24, Name UW ID#

Goals of this Lecture

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation

Objectives. ICT106 Fundamentals of Computer Systems Topic 8. Procedures, Calling and Exit conventions, Run-time Stack Ref: Irvine, Ch 5 & 8

Pointers and References

Object-Oriented Programming for Scientific Computing

Today. Putting it all together

CIT Week13 Lecture

3/7/2018. Sometimes, Knowing Which Thing is Enough. ECE 220: Computer Systems & Programming. Often Want to Group Data Together Conceptually

CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Data Structure Layout. In HERA/Assembly

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

VARIABLES AND TYPES CITS1001

ECE 15B COMPUTER ORGANIZATION

Introduction to C: Pointers

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

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

CS 241 Honors Memory

Project 3 Due October 21, 2015, 11:59:59pm

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

CPSC 427: Object-Oriented Programming

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

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Lecture V Toy Hardware and Operating System

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

The Procedure Abstraction

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

Inheritance, Polymorphism and the Object Memory Model

Operator overloading

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const.

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

Transcription:

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

const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed in a different way (unless the object itself is constant) example

const references

const references for return values What is the difference between these two versions of g? const Remember ch.8: Using the return value of a function as lvalue

solution

const references for arguments If you know the function will respect the constness of an object, making the argument a const reference will allow the function to be used in all situations. This means that: for built-in types, the function will not modify the argument for user-defined types, the function will call only const member functions, and won t modify any public data members.

QUIZ One of the function calls is incorrect. Which one and why?

Solution One of the function calls is incorrect. Which one and why?

Remember from C: pointer-to-pointer, a.k.a. second-level pointer

QUIZ: What does this program print?

Solution

Solution

It is possible to pass a pointer-to-pointer as argument but in C++ we can pass a pointer reference (reference to a pointer) instead! Read from R to L!

In C++, we can pass a pointer reference (reference to a pointer): Make sure you grok this pointer arithmetic! EOL 1

The copy-constructor Passing & returning by value a.k.a. A little bit of assembly language and computer architecture

The definition of function f is elsewhere We re showing the (simplified) assembly code that implements this line Arguments pushed on stack from right to left Beginning address of f s code is loaded in Program Counter. When f() - code returns, execution continues here.

This means 4 Bytes removed fro the stack. It depends on the sizes for int and char on this machine! In cdecl convention, the caller is responsible for cleaning up, i.e. restoring the stack. Do not confuse with the variable a. Functions return values in a specific register, known to the compiler, e.g. in an Intel CPU this is EAX.

Stack before f() is called b a

The complete picture: Function-call stack frame Stack before f() is called b a Return address Local variables

How does this change when passing a (large) userdefined object by value? Stack before f() is called b a Return address Local variables example

Array of 100 chars! The question is: How to return the result? (There aren t enough registers!)

One possible solution is to also push the return values on the stack: Array of 100 chars! Array of 100 chars! Return values

To understand why pushing return values on the stack is not good, we need to understand the constraints on the compiler when it s making a function call.

The compiler must use a solution that works with: Interrupts and ISRs = Interrupt Service Routines (functions, really!) Recursive functions

Interrupts Consider the following scenario: Function pushes return values on stack and returns normally Before the calling function has a chance to process the return values, an interrupt occurs, and the ISR overwrites them! Return values ISRs are smart enough to save all registers on the stack, and restore them upon exit, but they have their limits.

Re-entrancy Would placing the return values on the heap work? Why not? Return values

Historical note: In K&R C, it was not possible to return structs, only pointers to structs. Since C89, C functions can return structs, although many compilers don t actually place the struct on the stack they do return values optimization instead (where only a pointer is returned, e.g. in register eax). Not in text This means that the caller is responsible for setting up space for return values, contrary to C custom! Array of 100 chars! Array of 100 chars! Return values

The solution chosen in C++ is this: Push the address of the return value s destination on the stack as a hidden argument Let the function copy the return value into the destination before returning. B2 s address

What can go wrong when copying?

Similar to the text program C11:HowMany.cpp

When the value was returned in h2, the bit-copy mechanism did not increment objectcount, but when h2 went out of scope, the destructor did decrement it!

Extra-credit

Conclusion The low-level, bit-by-bit copying doesn t always work correctly when combined with C++ constructors. We call this bitcopy, to distinguish it from copy-construction (next).

text

text [ ] intervene in this process and prevent the compiler from doing a bitcopy. You do this by defining your own function to be used whenever the compiler needs to make a new object from an existing object: We re making a new object, so this function is a constructor. The constructor has a single argument: the object we re constructing from. The argument is passed by (constant) reference! Example

This function is called whenever a new object is created from an existing one. In general: X(const X&)

QUIZ 16. Write a class CCClass with: An integer data member A constructor that initializes the data member A copy-constructor that simply announces itself to cout.

16. Now create: QUIZ a function that passes a CCClass object in by value and does not return anything another function that does not take any arguments, creates a local CCClass object, and returns it by value.

QUIZ 16. Call these functions in the main program.

How many times is the constructor called? How many times the copyconstructor?

What if we call the function, but ignore the return value? A: The compiler creates a temporary., so the C.C. is still called twice!

text Default copy-constructor Because the copy-constructor implements pass and return by value, it s important that the compiler creates one for you in the case of simple structures effectively, the same thing it does in C. However, all you ve seen so far is the default primitive behavior: a bitcopy. When more complex types are involved, the C++ compiler will still automatically create a copy-constructor if you don t make one. Again, a bitcopy doesn t make sense, because it doesn t necessarily implement the proper meaning.

Default copy-constructor Suppose you create a new class composed of objects of several existing classes. This is called, appropriately enough, composition, and it s one of the ways you can make new classes from existing classes. Remember composition from Ch.1!

Ch. 1: Introduction to Objects

Reusing the implementation Owner class Component class Composition

Composition example (not in text) Back to ch.11

Composition example (Ch.11)

Draw the UML class diagram for this program!

Conclusion To create a copy-constructor for a class that uses composition (and inheritance, which is introduced in Chapter 14), the compiler recursively calls the copy-constructors for all the member objects (and base classes, for inheritance). The process the compiler goes through to synthesize a copy-constructor is called memberwise initialization.

Is this program correct?

Is this program correct? No if any constructor exists (even only a copy-constructor), the compiler does not create a default constructor!

How about the opposite? Here we have a constructor, but no copyconstructor!

How about the opposite? Here we have a constructor, but no copyconstructor! What happened here, exactly?

Preventing pass-by-value There s a simple technique for preventing pass-by-value: declare a private copy-constructor. If the user tries to pass or return the object by value, the compiler will produce an error message because the copyconstructor is private. It can no longer create a default copy-constructor because you ve explicitly stated that you re taking over that job.

Preventing pass-by-value There s a simple technique for preventing pass-by-value: declare a private copy-constructor. If the user tries to pass or return the object by value, the compiler will produce an error message because the copyconstructor is private. It can no longer create a default copy-constructor because you ve explicitly stated that you re taking over that job.

Deleted functions were introduced in C++11

Section 8.4.3 A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed.

QUIZ: Does this program compile?

QUIZ: Does this program compile? EOL 2

Pointers to members A pointer is a variable that holds the address of some location. You can change what a pointer selects at runtime, and the destination of the pointer can be either data or a function. The C++ pointer-to-member follows this same concept, except that what it selects is a location inside a class.

Pointers to members The dilemma here is that a pointer needs an address, but there is no address inside a class; selecting a member of a class means offsetting into that class. You can t produce an actual address until you combine that offset with the starting address of a particular object. Examples

Remember how we access members of classes and structs: Examples

Remember how we declare and initialize ordinary pointers: int a = 42; int *aptr; aptr = &a; or int a = 42; int *aptr = &a; Examples

Let s say that we have a class with multiple members of the same type How do we create a pointer that can point to those members?

How to read this from R to L

QUIZ Create a class containing a double and a print( ) function that prints the double. Don t forget the constructor!

QUIZ In main( ), create a pointer to the data member.

QUIZ In main, create an object of your class and a pointer to that object.

QUIZ Manipulate the data member of the object, using the pointer inside the object.

QUIZ Create a pointer to the object, and the manipulate the data member of the object, using the pointer to the object and the pointer inside the object.

Pointers to members are quite limited: they can be assigned only to a specific location inside a class. We cannot increment or compare them like ordinary pointers.

SKIP the last section of ch.11: Pointers to member functions

Homework for ch. 11 Provided as separate handout (also available on our webpage --> agapie.net) Due Wednesday, Nov.15, at the beginning of class. Please hand in a hard-copy, do not email! EOL 2