C++ Friend Function to convert an octal number into binary
Write a program in C++ to convert an octal number into binary using friend function.
If we declare a function friend int cal(binary);
as a friend in a class binary
then this function friend int cal(binary);
can access the private and protected members of the class binary
. You must know that a global function can also be declared as a friend function of the class.
Syntax of friend function in C++
class class_name
{
…
friend return_type function_name(arguments);
…
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | #include<iostream> using namespace std; class binary { private: long int octalnum,p=1; long int dec=0,i=1,j,d; long int binno=0; public: binary() { cout<<"Enter an octal number to convert: "; cin>>octalnum; for(j=octalnum;j>0;j=j/10) { d=j%10; if(i==1) { p=p*1; } else { p=p*8; } dec=dec+(d*p); i++; } i=1; for(j=dec;j>0;j=j/2) { binno=binno+(dec%2)*i; i=i*10; dec=dec/2; } } friend int cal(binary); }; int cal(binary b) { cout<<"Your input Octal number is: "<<b.octalnum<<endl; cout<<"Octal number "<<b.octalnum<<" equalant to Binary "<<b.binno; } int main() { binary b; cal(b); } |
Output
Enter an octal number to convert: 5
Octal number 5 is equivalent to Binary: 101