FRIEND FUNCTIONS IN CPP

Similar documents
UNIT -1: Introduction to C++

Overloading Operators in C++

PIC 10A. Lecture 17: Classes III, overloading

4. Structure of a C++ program

Introduction Of Classes ( OOPS )

Friends and Overloaded Operators

Friends and Overloaded Operators

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

AN OVERVIEW OF C++ 1

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CS 247: Software Engineering Principles. ADT Design

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

Object Oriented Design

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Short Notes of CS201

G52CPP C++ Programming Lecture 13

NAMESPACES IN C++ You can refer the Programming with ANSI C++ by Bhushan Trivedi for Understanding Namespaces Better(Chapter 14)

C++ For Science and Engineering Lecture 15

CS201 - Introduction to Programming Glossary By

Recharge (int, int, int); //constructor declared void disply();

III. Classes (Chap. 3)

Time(int h, int m, int s) { hrs = h; mins = m; secs = s; } void set(int h, int m, int s) { hrs = h; mins = m; secs = s; }

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

Object Oriented Design

Friend Functions and Friend Classes

VARIABLES & ASSIGNMENTS

Use the dot operator to access a member of a specific object.

mywbut.com Inheritance

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Chapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Object-Oriented Programming

Recap: Pointers. int* int& *p &i &*&* ** * * * * IFMP 18, M. Schwerhoff

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

CSCE 110 PROGRAMMING FUNDAMENTALS

Inheritance, and Polymorphism.

Exceptions, Case Study-Exception handling in C++.

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Object-Oriented Programming (OOP) Fundamental Principles of OOP

COSC 320 Exam 2 Key Spring Part 1: Hash Functions

Module Operator Overloading and Type Conversion. Table of Contents

CSCE Practice Midterm. Data Types

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

System Design and Programming II

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Ch 8. Operator Overloading, Friends, and References

CMSC 202 Midterm Exam 1 Fall 2015

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Chapter 15 - C++ As A "Better C"

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Introduction to C++ Systems Programming

CSCE 206: Structured Programming in C++

Fast Introduction to Object Oriented Programming and C++

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

pointers + memory double x; string a; int x; main overhead int y; main overhead

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Review Questions for Final Exam

Constructor - example

Name Section: M/W or T/TH. True or False (14 Points)

1. (25 pts) Short Answer. Provide brief (1-3 sentence) answers to the following:

Object-Oriented Programming in C++

C++_ MARKS 40 MIN

Lecture 23: Pointer Arithmetic

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

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

OBJECT ORIENTED PROGRAMMING USING C++

Data Structures using OOP C++ Lecture 3

CSE 303: Concepts and Tools for Software Development

Due Date: See Blackboard

Functions, Arrays & Structs

Fundamentals of Programming. Lecture 19 Hamed Rasifard

moretosearch = (location < length);

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

W3101: Programming Languages C++ Ramana Isukapalli

Linked List using a Sentinel

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Implementing Abstract Data Types (ADT) using Classes

VIRTUAL FUNCTIONS Chapter 10

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

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

The American University in Cairo Department of Computer Science & Engineeringt CSCI &09 Dr. KHALIL Exam-I Fall 2009

C++ 8. Constructors and Destructors

As an example using arrays, let s write some code to get started with the Upthrust game. We can use a 2D array to represent the game board.

CE221 Programming in C++ Part 1 Introduction

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

C++ Scope Resolution Operator ::

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

TEMPLATES AND EXCEPTION HANDLING

Transcription:

FRIEND FUNCTIONS IN CPP Friend Functions It is possible to grant a nonmember function access to the private members of a class by using a friend. A friend function has access to all private and protected members of the class for which it is a friend. To declare a friend function, include its prototype within the class, preceding it with the keyword friend. Consider this program: #include <iostream> using namespace std; class myclass int a, b; friend int sum(myclass x); void set_ab(int i, int j); ; void myclass::set_ab(int i, int j) a = i; b = j; // Note: sum() is not a member function of any class. int sum(myclass x) /* Because sum() is a friend of myclass, it can directly access a and b. */ return x.a + x.b; int main() myclass n; n.set_ab(3, 4); cout << sum(n);

return 0; In this example, the sum( ) function is not a member of myclass. However, it still has full access to its private members. Also, notice that sum( ) is called without the use of the dot operator. Because it is not a member function, it does not need to be (indeed, it may not be) qualified with an object's name. Although there is nothing gained by making sum( ) a friend rather than a member function of myclass, there are some circumstances in which friend functions are quite valuable. First, friends can be useful when you are overloading certain types of operators (see Chapter 14). Second, friend functions make the creation of some types of I/O functions easier (see Chapter 18). The third reason that friend functions may be desirable is that in some cases, two or more classes may contain members that are interrelated relative to other parts of your program. Let's examine this third usage now. To begin, imagine two different classes, each of which displays a pop-up message on the screen when error conditions occur. Other parts of your program may wish to know if a pop-up message is currently being displayed before writing to the screen so that no message is accidentally overwritten. Although you can create member functions in each class that return a value indicating whether a message is active, this means additional overhead when the condition is checked (that is, two function calls, not just one). If the condition needs to be checked frequently, this additional overhead may not be acceptable. However, using a function that is a friend of each class, it is possible to check the status of each object by calling only this one function. Thus, in situations like this, a friend function allows you to generate more efficient code. The following program illustrates this concept: #include <iostream> using namespace std; const int IDLE = 0; const int INUSE = 1; class C2; // forward declaration class C1

int status; // IDLE if off, INUSE if on screen friend int idle(c1 a, C2 b); ; class C2 int status; // IDLE if off, INUSE if on screen friend int idle(c1 a, C2 b); ; void C1::set_status(int state) void C2::set_status(int state) int idle(c1 a, C2 b) if(a.status b.status) return 0; else return 1; int main() C1 x; C2 y; x.set_status(idle);

y.set_status(idle); if(idle(x, y)) cout << "Screen can be used.\n"; x.set_status(inuse); if(idle(x, y)) cout << "Screen can be used.\n"; return 0; Notice that this program uses a forward declaration (also called a forward reference) for the class C2. This is necessary because the declaration of idle( ) inside C1 refers to C2 before it is declared. To create a forward declaration to a class, simply use the form shown in this program. A friend of one class may be a member of another. For example, here is the preceding program rewritten so that idle( ) is a member of C1: #include <iostream> using namespace std; const int IDLE = 0; const int INUSE = 1; class C2; // forward declaration class C1 int status; // IDLE if off, INUSE if on screen int idle(c2 b); // now a member of C1 ; class C2 int status; // IDLE if off, INUSE if on screen

friend int C1::idle(C2 b); ; void C1::set_status(int state) void C2::set_status(int state) // idle() is member of C1, but friend of C2 int C1::idle(C2 b) if(status b.status) return 0; else return 1; int main() C1 x; C2 y; x.set_status(idle); y.set_status(idle); if(x.idle(y)) cout << "Screen can be used.\n"; x.set_status(inuse); if(x.idle(y)) cout << "Screen can be used.\n"; return 0; Because idle( ) is a member of C1, it can access the status variable of objects of type C1 directly. Thus, only objects of type C2 need be passed to idle( ). There are two important

restrictions that apply to friend functions. First, a derived class does not inherit friend functions. Second, friend functions may not have a storage-class specifier. That is, they may not be declared as static or extern.