Friend Functions and Friend Classes

Similar documents
Constructors.

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CS 247: Software Engineering Principles. ADT Design

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

Fast Introduction to Object Oriented Programming and C++

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Programming Abstractions

Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle s(0,0,4,4)

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

Dot and Scope Resolution Operator

a data type is Types

ENCAPSULATION AND POLYMORPHISM

Chapter 4 Defining Classes I

Data Structures (INE2011)

ADTs & Classes. An introduction

Constructors for classes

CS24 Week 3 Lecture 1

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

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Protection Levels and Constructors The 'const' Keyword

G52CPP C++ Programming Lecture 13

Encapsulation in C++

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

QUIZ Friends class Y;

CIS 190: C/C++ Programming. Classes in C++

C++ Important Questions with Answers

What are the characteristics of Object Oriented programming language?

Crash Course into. Prof. Dr. Renato Pajarola

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

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

B16 Object Oriented Programming

Overloading Operators in C++

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Ch 8. Operator Overloading, Friends, and References

B16 Object Oriented Programming

CLASS DESIGN. Objectives MODULE 4

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

Inheritance, and Polymorphism.

CS105 C++ Lecture 7. More on Classes, Inheritance

Ch. 10: Name Control

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

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

QUIZ. How could we disable the automatic creation of copyconstructors

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

Functions, Pointers, and the Basics of C++ Classes

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming in C#

Implementing Abstract Data Types (ADT) using Classes

Defining Class Functions.

G52CPP C++ Programming Lecture 17

Introduction to Java. Handout-1d. cs402 - Spring

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CMSC 202 Midterm Exam 1 Fall 2015

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Intermediate Programming & Design (C++) Classes in C++

Abstract Data Types (ADT) and C++ Classes

CS 31 Discussion 1A, Week 8. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

A First Object. We still have another problem. How can we actually make use of the class s data?

Object Oriented Software Design II

Computer Science II CSci 1200 Lecture 18 Operators and Friends

FRIEND FUNCTIONS IN CPP

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Object-Oriented Programming, Iouliia Skliarova

G52CPP C++ Programming Lecture 9

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

Introduction to Programming Using Java (98-388)

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Principles of Object Oriented Programming. Lecture 4

CSE 303: Concepts and Tools for Software Development

Chapter 1: Object-Oriented Programming Using C++

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

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

4/27/2014. Templates II. Warmup Write the templated Swap function. Class Templates CMSC 202

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Question 1 Consider the following structure used to keep employee records:

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

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

Data Structures using OOP C++ Lecture 3

Introduction to Classes

COEN244: Class & function templates

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Chapter 4. Defining Classes I

Lecture 5: Methods CS2301

Lecture 14: more class, C++ streams

Review Questions for Final Exam

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Short Notes of CS201

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

QUIZ. How could we disable the automatic creation of copyconstructors

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

COMP322 - Introduction to C++

Transcription:

Friend Functions and Friend Classes C++ allows you to declare another class to be a friend of the current class to make it easier to access variables. OOP purists have criticized this feature as weakening the principles of encapsulation and information hiding. You can do everything you might want to do without using the friend feature. For example, Java is not friendly. There is no friend feature. However, this feature can make some code easier to write (at least in the short term; arguably not in the long term). You may also see other code that uses friends, so it is good to know what it means. Consider the following Employee class: ; Employee::Employee() : name(""), salary(0) Employee::Employee(string n, double s): name(n), salary(s) string Employee::getName() return name; double Employee::getSalary() return salary; We could add more functions but that will suffice to keep it simple. In this case we are doing our standard encapsulation with private variables. Now let s say we d like to write a Boss class where the boss is the supervisor of some employee: class Boss Boss(); void giveraise(double amount); Employee e; ; Boss::Boss() void Boss::giveRaise(double amount) e.salary = e.salary + amount; cout << e.salary << endl; This code won t work because the Boss class is not allowed to access the salary variable in the Employee class. The standard fix is to write an accessor and mutator method/function for the Employee class so we can get and set the variable.

However, one can argue that a boss should intrinsically have access to private variables in the Employee class. If you agree, then the friend modifier allows this to happen. Inside the Employee class we designate that Boss is Employee s friend. It doesn t matter if we put it in the private or public areas: friend class Boss; ; It s that simple, now the code will compile and the Boss class is allowed to access private variables and functions inside the Employee class. If you prefer you can also specify only single functions as a friend that can access any private variables in the class. To do this use the friend keyword in front of the function declaration. This makes the function technically not a member of the class, so we have to pass any object that we want to work on as a parameter instead of invoking it with the dot operator. The following gives access to the raisesalary function only: friend void raisesalary(double a, Employee &e); ; // Note: No Employee:: because raisesalary is NOT a member of the // Employee class! It is a friend as a global function // Because of this, we have to pass the object as a parameter // (e.g. raisesalary(amt, empobj) // instead of using it to invoke the function (e.g. empobj.raisesalary) void raisesalary(double a, Employee &e) e.salary += a; // Normally not allowed to access e.salary

Now our code to give a raise looks like this: Boss::Boss() void Boss::giveRaise(double amount) raisesalary(amount,e); cout << e.getsalary() << endl; This looks a little funky because raisesalary is really defined in the global namespace, not in the scope of the Employee object. Operator Overloading One place where friend functions are useful is when we overload operators. This is a handy feature that is not yet possible in Java although it has been discussed for future versions. In normal overload we can write multiple functions and C++ invokes the one that matches the parameter list. We have been doing this for constructors. You can also overload operators, like == or * or +. This can be really useful when you want to run your own code to determine with equality means or what + should do when you add two classes together. Let s return to our simple version of the Employee class: ; Employee::Employee() : name(""), salary(0) Employee::Employee(string n, double s): name(n), salary(s) string Employee::getName() return name; double Employee::getSalary() return salary; What if we would like to compare two Employee objects? C++ will give an error message because we haven t defined how to compare to Employee objects: Employee e2("bob",50); cout << (e1 == e2) << endl;

To do this we need to define the == operator. We can do it like this: friend bool operator==(employee& e1, Employee& e2); ; bool operator==(employee& e1, Employee& e2) // Since this is a friend we can access the private variables return (e1.name == e2.name); Our code will now run, and will print out a non-zero value since the two names are the same (it should output 1). In this case, e1 is the Employee object on the left side of the equality, and e2 is the Employee object on the right side of the equality. Here is another example where we override the += operator so it adds together the salaries and stores the sum into the Employee on the left hand side: friend bool operator==(employee& e1, Employee& e2); friend void operator+=(employee& e1, Employee& e2); ; void operator+=(employee& e1, Employee& e2) e1.salary += e2.salary;

int main() Employee e2("bill",50); e1 += e2; cout << e1.getsalary() << " " << e2.getsalary() << endl; // 100 and 50 return 0; Sometimes you don t want to change an object s value. For example, you might want to add two items together but not change e1 or e2. Here is one final example: friend Employee operator+(employee& e1, Employee& e2); Employee operator+(employee& e1, Employee& e2) Employee temp; temp.name = e1.name + " and " + e2.name; temp.salary = e1.salary + e2.salary; return temp; int main() Employee e2("bill",50); Employee e3 = e1 + e2; cout << e3.getsalary() << " " << e3.getname() << endl; // Outputs 100 Bob and Bill return 0; There s a bit going on under the hood. When we invoke +, the temp employee gets the concatenated name and sum of the salaries. When it is returned, the temp Employee is copied (using C++ s semantics for the assignment operator, i.e. it copies the name and salary) to the e3 variable. We then output e3. e1 and e2 are unchanged.

Overloading an operator as a member function It is also possible to overload an operator as a member function. Here is an example with the == operator: bool operator==(employee& e2); // No friend needed ; // Note that bool is a member function, not a global function // We don t need friend since it is a member function and has // access to private variables bool Employee::operator==( Employee& e2) // Use this-> to access the name of the calling object return (this->name == e2.name); We would invoke this the same way as before: Employee e2("bob",50); cout << (e1 == e2) << endl; In this case, e1 becomes the calling object so access this->name inside the == operator is accessing e1.name and e2 becomes e2.name. In other words, the compiler translates (e1 == e2) into e1.==(e2). It seems like this is a much better solution than using friends! It can be, but has a shortcoming. The shortcoming is that the variable on the left hand side of == has to be an Employee object. If it was something else we are trying to typecast into Employee then it won t work. For example, if we overload the + operator and want to allow e1 + 10, then e1 + 10 would work but 10 + e1 would fail because 10 is not a class. For this reason, the symmetric version of overloading operators using friends is the more common approach. Const Confusion Often we might use the const keyword with an overloaded operator if we don t want an operand to change. C++ lets us use the keyword const to make things constant and unchangeable, but it can be used in many different ways that can be confusing.

const int x = 3; int const x = 3; and both make x a constant that is an integer set to 3. You can t change x. In general, the thing to the left is what the const applies to, unless there is nothing there, in which case the const applies to the thing to the right. Const can also be used for a return type. Consider this: int& foo() static int x = 0; return x; main: cout << foo()++ << endl; cout << foo() << endl; This outputs 0 and then 1, because the ++ changes the return value which references the static variable. If you want to return a reference for efficiency purposes but don t want it changeable then you can make it const: const int& foo() Const can also be used with parameter passing. You might want to pass something by reference to save memory, but really don t want the parameter to be changed. In this case you can make it const: void foo(const big_class &parameter) Finally, const can be used in OOP to specify that a function can t change any instance (member) variables in the object. To do this stick const at the end of the function in the header and implementation file: class Fraction void print() const; void Fraction::print() const cout << m_numerator << / << m_denominator << endl; You can combine these to be extra confusing! const int& myfunction(const MyClass& parm) const