BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

C++ Tutorial - Friend Functions and Friend Classes - 2020

cplusplus_icon.png




Bookmark and Share





bogotobogo.com site search:




Friend Functions

The private member data of a class can be accessed only by member functions of that class.


Well, there is one exception. A friend function will be friendly with a class even though it is not a member of that class and can access the private members of the class.

#include <iostream>
using namespace std;

class Rectangle {
	int width, height;

public:
	Rectangle(int w = 1, int h = 1):width(w),height(h){} 
	friend void display(Rectangle &);
};

void display(Rectangle &r) {
	cout << r.width * r.height << endl;
}

int main () {
	Rectangle rect(5,10);
	display(rect);
	return 0;
}

We make a function a friend to a class by declaring a prototype of this external function within the class, and preceding it with the keyword friend

	friend void display(Rectangle &);

The friend function display(rect) has an access to the private member of the Rectangle class object though it's not a member function. It gets the width and height using dot: r.width and r.height. If we do this inside main, we get an error because they are private members and we can't access them outside of the class. But friend function to the class can access the private members.

But what's the point of friend functions. In the above example, we could have made "display" as a member function of the class instead of declaring it as a friend function to the class.

Why do we need friend functions?

A friend function can be friendly to 2 or more classes. The friend function does not belong to any class, so it can be used to access private data of two or more classes as in the following example.

#include <iostream>
using namespace std;

class Square;  // forward declaration

class Rectangle {
	int width, height;

public:
	Rectangle(int w = 1, int h = 1):width(w),height(h){} 
	friend void display(Rectangle &, Square &);
};

class Square {
	int side;

public:
	Square(int s = 1):side(s){} 
	friend void display(Rectangle &, Square &);
};

void display(Rectangle &r, Square &s) {
	cout << "Rectangle: " << r.width * r.height << endl;
	cout << "Square: " << s.side * s.side << endl;
}

int main () {
	Rectangle rec(5,10);
	Square sq(5);
	display(rec,sq);
	return 0;
}

Output is:

Rectangle: 50
Square: 25

The friend functions can serve, for example, to conduct operations between two different classes. Generally, the use of friend functions is out of an object-oriented programming methodology, so whenever possible it is better to use members of the same class to perform operations with them as in the following example getting exactly same output.

#include <iostream>
using namespace std;

class Rectangle {
	int width, height;

public:
	Rectangle(int w = 1, int h = 1):width(w),height(h){} 
	void display() {
		cout << "Rectangle: " << width * height << endl;
	};
};

class Square {
	int side;

public:
	Square(int s = 1):side(s){} 
	void display() {
		cout << "Square: " << side * side << endl;
	};
};

int main () {
	Rectangle rec(5,10);
	Square sq(5);
	rec.display();
	sq.display();
	return 0;
}

Summary:

  1. Friend functions are not members of any class but they can access private data of the class to which they are a friend.
  2. Because they are not members of any class, you should not call them using the dot operator.


Friend Classes

Just like functions are made friends of classes, we can also make one class to be a friend of another class. Then, the friend class will have access to all the private members of the other class.

#include <iostream>
using namespace std;

class Square;

class Rectangle {
	int width, height;

public:
	Rectangle(int w = 1, int h = 1):width(w),height(h){} 
	void display() {
		cout << "Rectangle: " << width * height << endl;
	};
	void morph(Square &);
};

class Square {
	int side;

public:
	Square(int s = 1):side(s){} 
	void display() {
		cout << "Square: " << side * side << endl;
	};
	friend class Rectangle;
};

void Rectangle::morph(Square &s) {
	width = s.side;
	height = s.side;
}

int main () {
	Rectangle rec(5,10);
	Square sq(5);
	cout << "Before:" << endl;
	rec.display();
	sq.display();

	rec.morph(sq);
	cout << "\nAfter:" << endl;
	rec.display();
	sq.display();
	return 0;
}

We declared Rectangle as a friend of Square so that Rectangle member functions could have access to the private member, Square::side

In our example, Rectangle is considered as a friend class by Square but Rectangle does not consider Square to be a friend, so Rectangle can access the private members of Square but not the other way around.






bogotobogo.com site search:


C++ : Where friends have access to your private members.
- Gavin Russell Baker







Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master