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

Similar documents
QUIZ Friends class Y;

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. What are 3 differences between C and C++ const variables?

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

QUIZ. Can you find 5 errors in this code?

QUIZ. Source:

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors

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

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

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?

Ch. 12: Operator Overloading

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

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

Ch. 10: Name Control

Lecture 13: more class, C++ memory management

Introduction to C++ with content from

Data Abstraction. Hwansoo Han

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

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Chapter 9 :: Data Abstraction and Object Orientation

10. Abstract Data Types

Chapter 1 Getting Started

Lecturer: William W.Y. Hsu. Programming Languages

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

Chapter 10 :: Data Abstraction and Object Orientation

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

C++ Inheritance and Encapsulation

CS11 Intro C++ Spring 2018 Lecture 1

Lecture Topics. Administrivia

PIC 10A Objects/Classes

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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

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

CMSC202 Computer Science II for Majors

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

Chapter 10 Introduction to Classes

D Programming Language

Object Oriented Design

Fast Introduction to Object Oriented Programming and C++

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

Lecture 14: more class, C++ streams

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

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Object Oriented Programming. Solved MCQs - Part 2

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

Interview Questions of C++

1. Write two major differences between Object-oriented programming and procedural programming?

CPS 506 Comparative Programming Languages. Programming Language

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

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

Review of the C Programming Language for Principles of Operating Systems

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

Separate Compilation Model

The object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space.

III. Classes (Chap. 3)

Chapter 6 Introduction to Defining Classes

CS201 Some Important Definitions

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Review of the C Programming Language

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

CSE 303: Concepts and Tools for Software Development

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Defining Classes and Methods

1: Introduction to Object (1)

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

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Software Design and Analysis for Engineers

Spectroscopic Analysis: Peak Detector

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

One of the fundamental kinds of websites that SharePoint 2010 allows

CERTIFICATE IN WEB PROGRAMMING

Fundamentals of Programming Session 13

CMPT 117: Tutorial 1. Craig Thompson. 12 January 2009

Pointers and References

Classes. C++ Object Oriented Programming Pei-yih Ting NTOU CS

AN OVERVIEW OF C++ 1

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

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

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

Lecture 7. Log into Linux New documents posted to course webpage

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

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Fundamental Concepts and Definitions

CMSC 330: Organization of Programming Languages

Lecture 18 Tao Wang 1

CS11 Introduction to C++ Fall Lecture 1

STUDENT LESSON A5 Designing and Using Classes

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

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

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

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

OpenACC Course. Office Hour #2 Q&A

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Chapter 5. Names, Bindings, and Scopes

Object-Oriented Programming

Transcription:

Friends We want to explicitly grant access to a function that isn t a member of the current class/struct. This is accomplished by declaring that function (or an entire other struct) as friend inside the class/struct declaration.

This wouldn t work without the previous declaration of X This wouldn t work without the previous declaration of y Also serves as prototype for the global function h Also serves as prototype for the global function g

Why do we need to declare g and h as friends of X?

Why do we need to declare Z as friend of X?

The fine print

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.

text Conclusion on friends In a pure OOL, only member functions would have access to the private members friend is introducing an exception C++ is a hybrid object-oriented language, not a pure one, and friend was added to get around practical problems that crop up. It s fine to point out that this makes the language less pure, because C++ is designed to be pragmatic, not to aspire to an abstract ideal.

Nested friends A nested class is a member of the enclosing class, and as such has unrestricted access to all other members (private or public). The members of an enclosing class have no special access to members of a nested class. This was only introduced in C++11 standard! The text example C05:NestFriend.cpp is pre- C++11, that s why the nested class is declared as friend. This was the case since the 1980s.

Nested friends Example not in text

Nested friends Example not in text

Skip the text example C05:NestFriend.cpp except the following useful tidbit

What does this function do? The Standard C library function memset( ) (in <cstring>) is used for convenience in the program above. It sets all memory starting at a particular address (the first argument) to a particular value (the second argument) for n bytes past the starting address (n is the third argument). Of course, you could have simply used a loop to iterate through all the memory, but memset( ) is available, well-tested (so it s less likely you ll introduce an error), and probably more efficient than if you coded it by hand.

Example not in text (it works in C, too) Beginning address of memory block to fill Character (Byte) to fill with How many positions to fill

Extra-credit quiz

Individual work for next time: Rewrite the code in Public.cpp and Private.cpp with class instead of struct. Further modify the member functions in both programs to print all the data members in their class. Enter and run the modified programs in the IDE of your choice.

QUIZ Why are friends impure?

QUIZ What are the 3 types of entity a class can befriend in C++? Which one requires a fwd. declaration and which ones don t?

solution 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 Do nested structs automatically have access to the private members of the outer struct?

Object layout Within a particular access block (a group of declarations delimited by access specifiers), the variables are guaranteed to be laid out contiguously, as in C. However, the access blocks may not appear in the object in the order that we declare them.

Object layout Although the compiler will usually lay the blocks out exactly as you see them, there is no rule about it, because a particular machine architecture and/or operating environment may have explicit support for private and protected that might require those blocks to be placed in special memory locations. The language specification doesn t want to restrict this kind of advantage.

Access specifiers are part of the structure and don t affect the objects created from the structure. All of the access specification information disappears before the program is run; generally this happens during compilation. In a running program, objects become regions of storage and nothing more. If you really want to, you can break all the rules and access the memory directly, as you can in C. C++ is not designed to prevent you from doing unwise things. It just provides you with a much easier, highly desirable alternative.

The class In the original OOP language, Simula-67, the keyword class was used to describe a new data type. This apparently inspired Stroustrup to choose the same keyword for C++, to emphasize that this was the focal point of the whole language: the creation of new data types that are more than just C structs with functions. However, the use of class in C++ comes close to being an unnecessary keyword. It s identical to the struct keyword in absolutely every way except one: class defaults to private, whereas struct defaults to public.

A note on style vs. Public first Private first

Some programmers like it, for others it is overkill: Because mx is already hidden in the scope of Y, the m (for member ) is unnecessary. However, in projects with many global variables (something you should strive to avoid, but which is sometimes inevitable in existing projects), it is helpful to be able to distinguish inside a member function definition which data is global and which is a member.

QUIZ Write the interface for a class called Quadratic, with 4 double members: the 3 coefficients a, b, c, and the determinant det. What member functions would you propose? Make sure you use access specifiers!

Read Modifying Stash to use access control

Handle classes Access control in C++ allows you to separate interface from implementation, but the implementation hiding is only partial. The compiler must still see the declarations for all parts of an object in order to create and manipulate it properly. Including the private ones

Handle classes Can we put the private part of a class in a separate file? A: Yes! This solution is called a Handle class.

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.

Solution: Place public interface in header file, and move all private stuff in implementation (.cpp) file. This technique is called handle classes or the Cheshire cat everything about the implementation disappears (from the header file) except for a single pointer, the smile.

A.k.a.: incomplete type specification fwd. declaration (as in friends!) class prototype (as for functions)

The private structure body is hidden away in the implementation file: Nested struct Etc.

This is the layout of the project, with the 2.cpp files and one header:

End-of-chapter problem: solution

I changed this value! See console messages from building on next slide

Console messages from building (compiling + linking) the project in MSVS Initial build Build after modifying only implementation file

Homework for chs.4+5 Provided on our webpage --> agapie.net Due Mon., March 5 Please hand in a hard-copy, do not email! EOL 2