C++ programs
Write a C++ program to return and pass objects to stand-alone functions or friend function using call by value and call by reference.
Write a C++ program to return and pass objects to
• stand-alone functions using call by value.
• Friend function using call by reference.
PROGRAM:
• CALL BY VALUE
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
class complex
{
private:
float real,imag;
public:
complex()
{
real=imag=0;
}
complex(float r,float i)
{
real=r;
imag=i;
}
void getdata()
{
float r,i;
cout<<"www.adkool.com";
cout<<endl<<"\nEnter real and imaginary part : ";
cin>>r>>i;
real=r;
imag=i;
}
void displaydata()
{
cout<<"www.adkool.com";
cout<<real<<" + "<<imag<<"i";
}
void add_complex(complex &c1,complex &c2)
{
cout<<"\n\nAddition : ";
real=c1.real+c2.real;
imag=c1.imag+c2.imag;
}
complex mul_complex(complex &c2)
{
cout<<"www.adkool.com";
cout<<"\n\nMultiplication : ";
complex t;
t.real=real*c2.real-imag*c2.imag;
t.imag=real*c2.imag+c2.real*imag;
return t;
}
};
void main()
{
clrscr();
complex c1,c2,c3,c4;
c1.getdata();
c2.getdata();
c3.add_complex(c1,c2);
c3.displaydata();
c4=c3.mul_complex(c2);
c4.displaydata();
getch();
}
OUTPUT
Enter real and imaginary part : 5 2
Enter real and imaginary part : 4 9
Addition : 9 + 11i
Multiplication : -63 + 125i
• FRIEND FUNCTION USING CALL BY REFERENCE
PROGRAM:
#include<iostream.h>
#include<conio.h>
class PQR;
class ABC;
class ABC
{
int x;
public:
ABC() : x(10){}
void display()
{
cout<<"\nValue of x : "<<x<<endl;
}
friend void swap(ABC &,PQR&);
};
class PQR
{
int y;
public:
PQR() : y(20){}
void display()
{
cout<<"\nValue of y : "<<y<<endl;
}
friend void swap(ABC &,PQR &);
};
void swap(ABC &A,PQR &P)
{
int temp;
temp=A.x;
A.x=P.y;
P.y=temp;
}
void main()
{
clrscr();
ABC obj1;
PQR obj2;
cout<<"\n\nBefore swapping :- \n";
obj1.display();
obj2.display();
swap(obj1,obj2);
cout<<"\n\nAfter swapping :- \n";
obj1.display();
obj2.display();
cout<<endl;
getch();
}
OUTPUT
Before swapping :-
Value of x : 10
Value of y : 20
After swapping :-
Value of x : 20
Value of y : 10