How to defined and use friend function in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

class Test {
	int n;
public:
	Test(int _n) { n = _n; }
	friend int pos(Test o); // friend function
};

// friend function is defined outside that class and can 
// access all private and protected members of the class
int pos(Test o)
{
	return (o.n > 0) ? 1 : 0;
}

int main()
{
	Test obj(13);

	if (pos(obj))
		cout << "yes" << endl;
	else
		cout << "no" << endl;


	return 0;
}



/*
run:

yes

*/

 



answered Mar 24, 2018 by avibootz

Related questions

1 answer 222 views
1 answer 217 views
1 answer 132 views
132 views asked Mar 24, 2018 by avibootz
3 answers 327 views
1 answer 223 views
1 answer 185 views
...