I am reading C++ Primer book. It says:
A friend declaration only specifies access. It is not a general declaration of the function. If we want users of the class to be able to call a friend function, then we must also declare the function separately from the friend declaration. To make a friend visible to users of the class, we usually declare each friend (outside the class) in the same header as the class itself.
Watch out for arrow in the code. Which asks my questions at those particular points in reference to above text.
header.h
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
#include <string>
using namespace std;
class Husband{
friend void change_salary(int changed_salary, Husband &ob);
public:
Husband() {}
Husband(unsigned new_salary) : salary{ new_salary } {}
private:
int salary;
};
//void change_salary(int changed_salary, Husband &ob); <----Code Compiles without even this declaration
#endif
main.cpp
#include "header.h"
void change_salary(int changed_salary, Husband &ob)
{
cout << "salary increased by 1000";
ob.salary = changed_salary;
}
int main()
{
Husband hs1{ 3000 };
change_salary(4000, hs1); // <---- Able to use function without explicit declaration outside of class in header
return 0;
}