friend class c++ code example

Example 1: friend function cpp reference

// friend functions
#include <iostream>
using namespace std;

class Rectangle {
    int width, height;
  public:
    Rectangle() {}
    Rectangle (int x, int y) : width(x), height(y) {}
    int area() {return width * height;}
    friend Rectangle duplicate (const Rectangle&);
};

Rectangle duplicate (const Rectangle& param)
{
  Rectangle res;
  res.width = param.width*2;
  res.height = param.height*2;
  return res;
}

int main () {
  Rectangle foo;
  Rectangle bar (2,3);
  foo = duplicate (bar);
  cout << foo.area() << '\n';
  return 0;
}

Example 2: friend class c++

class cl1{
private:
    int x;
    double u;
public:
	cl1();
    meth1();
    
friend class cl2; //to make friend class we are using friend keyword
};

class cl2{
private:
    int x;
    string y;
public:
	cl2();
    meth1();

friend class cl1; 
};

Tags:

Cpp Example