QUIZ Friends class Y;

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

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

QUIZ. Can you find 5 errors in this code?

Ch. 10: Name Control

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

QUIZ. Source:

Ch. 12: Operator Overloading

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

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

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 could we disable the automatic creation of copyconstructors

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

QUIZ. How could we disable the automatic creation of copyconstructors

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

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

G52CPP C++ Programming Lecture 9

Lecture 13: more class, C++ memory management

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

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

Implementing Abstractions

CSE 303: Concepts and Tools for Software Development

Lecture 14: more class, C++ streams

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

And Even More and More C++ Fundamentals of Computer Science

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

PIC 10A Objects/Classes

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

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

Chapter 1 Getting Started

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

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

10. Abstract Data Types

CS 3 Introduction to Software Engineering. 3: Exceptions

Exception Safe Coding

Chapter 10 :: Data Abstraction and Object Orientation

Mastering Data Abstraction or Get nit-picky on design advantages

Chapter 10 Introduction to Classes

Programming Style and Optimisations - An Overview

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

Client Code - the code that uses the classes under discussion. Coupling - code in one module depends on code in another module

C++ Inheritance and Encapsulation

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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

More loops Ch

Lecture 18 Tao Wang 1

Fast Introduction to Object Oriented Programming and C++

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

Software Design and Analysis for Engineers

Programming in C and C++

Chapter 11. Abstract Data Types and Encapsulation Concepts

The Dynamic Typing Interlude

CS 211 Programming Practicum Fall 2018

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

CS24 Week 3 Lecture 1

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

CS11 Introduction to C++ Fall Lecture 6

Auxiliary class interfaces

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Makefile Tutorial. Eric S. Missimer. December 6, 2013

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

CMSC162 Intro to Algorithmic Design II Blaheta. Lab March 2019

04-19 Discussion Notes

Chapter 9 :: Data Abstraction and Object Orientation

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

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

Object Oriented Software Design II


CS201 Some Important Definitions

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Chapter 13: Copy Control. Overview. Overview. Overview

C++ Style Guide. 1.0 General. 2.0 Visual Layout. 3.0 Indentation and Whitespace

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

Pointers, Arrays and Parameters

CS11 Intro C++ Spring 2018 Lecture 3

An Introduction to C++

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

! Mon, May 5, 2:00PM to 4:30PM. ! Closed book, closed notes, clean desk. ! Comprehensive (covers entire course) ! 30% of your final grade

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

OBJECT ORIENTED PROGRAMMING

Software Design and Analysis for Engineers

OBJECT ORIENTED PROGRAMMING USING C++

This section provides some reminders and some terminology with which you might not be familiar.

Interview Questions of C++

CS61C : Machine Structures

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

2 ADT Programming User-defined abstract data types

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11

Lecture 15: Even more pointer stuff Virtual function table

Templates Templates are functions or classes that are parameterized. We have already seen a few in STL:

The Design Process. General Development Issues. C/C++ and OO Rules of Thumb. Home

History C++ Design Goals. How successful? Significant constraints. Overview of C++

Lecturer: William W.Y. Hsu. Programming Languages

Software Design and Analysis for Engineers

Linked lists Tutorial 5b

Transcription:

QUIZ Friends class Y; Is a forward declaration neeed here?

QUIZ Friends

QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They are not needed for global functions or entire structs/classes.

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

Example projects where we don t want the implementation visible to the client programmer: The library header file may show proprietary info. that the company doesn t want available to competitors. Security (e.g. an encryption algorithm) don t want to expose any clues in a header file that might help people crack the code. Library is used in a hostile environment, where the programmers will try to directly access the private components anyway, using pointers and casting.

QUIZ Why can a.cpp file be made more secure than a header file?

QUIZ Why can a.cpp file be made more secure than a header file? Because it can be provided in the library in an already-compiled form, so the client programmers don t have access to the source code.

QUIZ What is the fragile base-class problem?

QUIZ The fragile base-class problem: Any time we make a change to a class (public interface or private member declarations), it is necessary to recompile all files that include that header file. For a large project in its early stages this can be very unwieldy because the underlying implementation may change often; if the project is very big, the time for compiles can prohibit rapid turnaround.

QUIZ What is a handle class?

QUIZ What is a handle class? A class that is accessed only through an opaque pointer; the class interface and definition are not available to the client programmer.

QUIZ How is a handle class implemented in C++?

QUIZ How is a handle class implemented in C++? With a forward declaration and a pointer:

Ch. 6: Initialization & Cleanup

Main ideas from chs. 4 and 5 Encapsulation (functions inside struct/class) Access control (hiding)

Two more safety issues: A large segment of C bugs occur when the programmer forgets to initialize or clean up a variable. This is especially true with C libraries, when client programmers don t know how to initialize a struct, or even that they must. (Libraries often do not include an initialization function, so the client programmer is forced to initialize the struct by hand.)

Two more safety issues: C programmers are comfortable with forgetting about variables once they are finished, so any cleaning up that may be necessary for a library s struct is often missed. What if we allocated memory dynamically for a large array? Memory leaks!

Guaranteed initialization with the constructor Both the Stash and Stack classes defined previously have a function called initialize( ), which hints by its name that it should be called before using the object in any other way. Unfortunately, this means the client programmer must ensure proper initialization by calling it.

Guaranteed initialization with the constructor In C++, initialization is too important to leave to the client programmer. The class designer can guarantee initialization of every object by providing a special function called the constructor. If a class has a constructor, the compiler automatically calls that constructor at the point an object is created, before client programmers can get their hands on the object.

Note that the constructor is in the public section of the interface! Name of constructor is the same as name of class.

What happens if we make the constructor private?

It is still possible to create objects of this class, but we have to use other member functions in Test, of friend functions. Conclusion: The constructor should be public (unless we have a good reason to the contrary).

the same thing happens as if a were an int: storage is allocated for the object. But [unlike an int] when the program reaches the sequence point (point of execution) where a is defined, the constructor is called automatically. That is, the compiler quietly inserts the call to X::X( ) for the object a at the point of definition.

Like any member function, the first (secret) argument to the constructor is the this pointer the address of the object for which it is being called. In the case of the constructor, however, this is pointing to an un-initialized block of memory, and it s the job of the constructor to initialize this memory properly.

QUIZ

QUIZ 3. Modify Exercise 1 so that the class contains an int member. Modify the constructor so that it takes an int argument that it stores in the class member. The constructor should print out the int value as part of its message, so you can see the objects as they are created. Create 2 objects of this class, with different arguments passed to the constructor.

Both constructor and destructor are unusual functions: they have no return value. This is distinctly different from a void return value, in which the function returns nothing but you still have the option to make it something else.

[ ] the compiler always makes these function calls itself, to make sure they happen properly. If there were a return value, and if you could select your own, the compiler would somehow have to know what to do with the return value, or the client programmer would have to explicitly call constructors and destructors, which would eliminate their safety.

We stop before the section Guaranteed cleanup with the destructor EOL 17

QUIZ What (if anything) is wrong with this code?

QUIZ How are constructors different from regular member functions?

QUIZ How are constructors different from regular member functions? They have the same name as the class They have no return type They are called automatically when objects are declared

QUIZ Can C++ structs have constructors?

QUIZ Can C++ structs have constructors? Yes, remember that there s only one difference between structs and classes in C++!

Guaranteed cleanup with the destructor No return type No arguments! Tilde Same name as the class

The destructor is called automatically by the compiler when the object goes out of scope. You can see where the constructor gets called by the point of definition of the object, but the only evidence for a destructor call is the closing brace of the scope that surrounds the object.

~Tree() is called here

QUIZ

QUIZ How are constructors and destructors: Similar? Different?

[ ] the destructor is still called, even when you use goto to jump out of a scope. (goto still exists in C++ for backward compatibility with C and for the times when it comes in handy.) You should note that a nonlocal goto, implemented by the Standard C library functions setjmp( ) and longjmp( ), doesn t cause destructors to be called. https://en.wikipedia.org/wiki/setjmp.h

Elimination of the definition block In C, you must always define all the variables at the beginning of a block, after the opening brace. [ ] it s good programming style. However: It has always seemed inconvenient to me to pop back to the beginning of a block every time I need a new variable. I find code more readable when the variable definition is close to its point of use.

Elimination of the definition block In C++, however, there s a significant problem in being forced to define all objects at the beginning of a scope: If a constructor exists, it must be called when the object is created. However, if the constructor takes one or more initialization arguments, how do you know you will have that initialization information at the beginning of a scope?

Doesn t matter whether we use braces or not the scope is always the body of the loop. (Of course, w/o braces, the body of the loop is only one command.)

QUIZ What will this code print?

Watch out for local variables that hide variables from the enclosing scope. In general, using the same name for a nested variable and a variable that is global to that scope is confusing and error-prone. I.e. have the same name as

I find small scopes an indicator of good design. If you have several pages for a single function, perhaps you re trying to do too much with that function. More granular functions are not only more useful, but they also make it easier to find bugs.

To make sure all objects are properly initialized, the compiler even checks to make sure that you don t put the object definition (and thus the constructor call) where the sequence point only conditionally passes through it, such as in a switch statement or somewhere a goto can jump past it.

Stash with constructors and destructors

Stack with constructors & destructors will be covered in the lab

Aggregate initialization An aggregate is just what it sounds like: a bunch of things clumped together. This definition includes aggregates of mixed types, like structs and classes. An array is an aggregate of a single type. Initializing aggregates can be error-prone and tedious. C++ aggregate initialization makes it much safer.

All these cases are identical to C:

All these cases are identical to C:

If any of the data members are private (which is typically the case for a well-designed class in C++), or even if everything s public but there s a constructor, things are different:

An example with constructors having multiple arguments:

Default constructors

You might think that the compiler-synthesized constructor should do some intelligent initialization, like setting all the memory for the object to zero. But it doesn t that would add extra overhead [ ] If you want the memory to be initialized to zero, you must do it yourself by writing the default constructor explicitly.

Another reason for lazy default constructors is that, in many cases, it is not clear what the default value should be for an object! E.g. How should be dates initialized?

Although the compiler will create a default constructor for you, the behavior of the compilersynthesized constructor is rarely what you want. You should treat this feature as a safety net, but use it sparingly. In general, you should define your constructors explicitly and not allow the compiler to do it for you.

Ambiguity: In the next chapter we shall encounter overloaded constructors:

There is no homework for ch. 6 assigned today! One homework will be assigned for 6 and 7 together. EOL 18