Friend Functions

Prototypes of friend functions are declared within a class preceded by the keyword friend and then followed by the function prototype signature, to allow external functions (i.e. the friends) to access private and protected members.

 

Syntax:

friend void display() ;

 

This will allow the display() function, defined outside the class, to access all members within the class:

#include <iostream>
#include <string>
using namespace std;

class Rider {
	string name ;
	int age, wins ;

	friend void display(Rider &) ;  //declaring the friend function

public:
	void setValues (string, int, int) ; //setter

	string getName() { return name; }  //getters
	int getAge() { return age; }
	int getChampionships() { return wins; }

	void hail() { cout << "All hail the " << wins << " times world champion!" << endl << endl ; }

} bayliss ; //note declaration of Rider object called bayliss

void Rider::setValues ( string name, int age, int wins) {
	this -> name = name ;  //using this for the current object
	this -> age = age ;
	this -> wins = wins ;
}

//implementation of the display() friend function
void display(Rider &rider){
	//note the direct private attributes are being referred to, not the methods to get the values!
	cout << rider.name << " is a " << rider.age << " year old motorcyclist, " ;
	cout << "who has won " << rider.wins << " world championships!" << endl ;
}

int main() {
	Rider rossi ; //declare Rider object called rossi
	Rider *myPtr = &rossi ;  //assign pointer to rossi object
	myPtr->setValues ("Valentino Rossi", 34, 9) ;  //set rossi object values
	display(*myPtr) ; //call display function passing in pointer to rossi object
	myPtr->hail() ;  //display rossi object class message

	myPtr = &bayliss ;  //reassign the pointer to the bayliss object
	myPtr->setValues ( "Troy Bayliss", 43, 3) ;
	display(*myPtr);
	myPtr->hail() ;

	return 0 ;
}

Compile & Run:

Valentino Rossi is a 34 year old motorcyclist, who has won 9 world championships!
All hail the 9 times world champion! 

 

Troy Bayliss is a 43 year old motorcyclist, who has won 3 world championships!
All hail the 3 times world champion!

Leave a Reply