Task1
Rectangle
Width:int
Height:int
Set_values(int,int):void
Area():int
GetWidth():int
GetHeight():int
According to the main() function and the output given below, create ‘Rectangle’ class and add a friend
function called ‘duplicate’ that will multiply the private data members (width and height) by 2.
void main () {
CRectangle rect;
rect.set_values (2,3);
cout<<"Before calling friend duplicate:"<<endl;
cout<<"Width:"<<rect.getwidth()<<endl;
cout<<"Height:"<<rect.getheight()<<endl;
duplicate (rect);
cout<<"After calling friend duplicate:"<<endl;
cout<<"Width:"<<rect.getwidth()<<endl;
cout<<"Height:"<<rect.getheight()<<endl<<endl;
cout<<"Area:"<<rect.area()<<endl;
system("pause");
}
Solution:
class CRectangle {
int width, height;
public:
void set_values (int, int);
int getheight();
int getwidth();
int area () {return (width * height);}
friend void duplicate (CRectangle&);
};
void CRectangle::set_values (int a, int b) {
width = a;
height = b;
}
int CRectangle::getheight()
{
return height;
}
int CRectangle::getwidth()
{
return width;
}
void duplicate (CRectangle &rect)
{
rect.width = rect.width*2;
rect.height = rect.height*2;
}
Sample output:
Before calling friend duplicate:
Width:2
Height:3
After calling friend duplicate:
Width:4
Height:6
Area:24
Task2
According to the main() function and output given below, create a class called ‘RectSq’ that will include the
‘Rectangle’ and ‘Square’ classes and add a function called ‘display’ that will be the friend of both classes. (Do
not forget to do forward declaration)
The friend function will have two parameters (objects of rectangle and square classes). Then the function will
calculate and print the area of both objects.
Hint: You should pass the parameters of the friend function by reference.
#include <iostream>
using namespace std;
#include"recsq.h"
void main () {
Rectangle rec(5,10);
Square sq(5);
display(rec,sq);
system(“pause”);
}
Output is:
Rectangle: 50
Square: 25
Rectangle
width:int
height:int
Rectangle(int=1,int=1)
Solution:
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 &);
};
Square
side:int
Square(int=1)
void display(Rectangle &r, Square &s) {
cout << "Rectangle: " << r.width * r.height << endl;
cout << "Square: " << s.side * s.side << endl;
}
#include <iostream>
using namespace std;
#include"recsq.h"
int main ()
{
Rectangle rec(5,10);
Square sq(5);
display(rec,sq);
system(“pause”);
}
© Copyright 2026 Paperzz