Skip to main content

C++: Friend and Math Function

C++ Friend function

If a function is defined as a friend function in C++, then the protected and private data of a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.

Declaration of friend function in C++

  1. class class_name    
  2. {    
  3.     friend data_type function_name(argument/s);            // syntax of friend function.  
  4. };    

In the above declaration, the friend function is preceded by the keyword friend. The function can be defined anywhere in the program like a normal C++ function. The function definition does not use either the keyword friend or scope resolution operator.

Characteristics of a Friend function:

  • The function is not in the scope of the class to which it has been declared as a friend.
  • It cannot be called using the object as it is not in the scope of that class.
  • It can be invoked like a normal function without using the object.
  • It cannot access the member names directly and has to use an object name and dot membership operator with the member name.
  • It can be declared either in the private or the public part.

C++ friend function Example

Let's see the simple example of C++ friend function used to print the length of a box.

  1. #include <iostream>    
  2. using namespace std;    
  3. class Box    
  4. {    
  5.     private:    
  6.         int length;    
  7.     public:    
  8.         Box(): length(0) { }    
  9.         friend int printLength(Box); //friend function    
  10. };    
  11. int printLength(Box b)    
  12. {    
  13.    b.length += 10;    
  14.     return b.length;    
  15. }    
  16. int main()    
  17. {    
  18.     Box b;    
  19.     cout<<"Length of box: "<< printLength(b)<<endl;    
  20.     return 0;    
  21. }    

Output:

Length of box: 10  

Let's see a simple example when the function is friendly to two classes.

  1. #include <iostream>  
  2. using namespace std;  
  3. class B;          // forward declarartion.  
  4. class A  
  5. {  
  6.     int x;  
  7.     public:  
  8.     void setdata(int i)  
  9.     {  
  10.         x=i;  
  11.     }  
  12.     friend void min(A,B);         // friend function.  
  13. };  
  14. class B  
  15. {  
  16.     int y;  
  17.     public:  
  18.     void setdata(int i)  
  19.     {  
  20.         y=i;  
  21.     }  
  22.     friend void min(A,B);                    // friend function  
  23. };  
  24. void min(A a,B b)  
  25. {  
  26.     if(a.x<=b.y)  
  27.     std::cout << a.x << std::endl;  
  28.     else  
  29.     std::cout << b.y << std::endl;  
  30. }  
  31.    int main()  
  32. {  
  33.    A a;  
  34.    B b;  
  35.    a.setdata(10);  
  36.    b.setdata(20);  
  37.    min(a,b);  
  38.     return 0;  
  39.  }  

Output:

10

In the above example, min() function is friendly to two classes, i.e., the min() function can access the private members of both the classes A and B.

C++ Friend class

A friend class can access both private and protected members of the class in which it has been declared as friend.

Let's see a simple example of a friend class.

  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. class A  
  6. {  
  7.     int x =5;  
  8.     friend class B;           // friend class.  
  9. };  
  10. class B  
  11. {  
  12.   public:  
  13.     void display(A &a)  
  14.     {  
  15.         cout<<"value of x is : "<<a.x;  
  16.     }  
  17. };  
  18. int main()  
  19. {  
  20.     A a;  
  21.     B b;  
  22.     b.display(a);  
  23.     return 0;  
  24. }  

Output:

value of x is : 5

In the above example, class B is declared as a friend inside the class A. Therefore, B is a friend of class A. Class B can access the private members of class A.

C++ Math Functions

C++ offers some basic math functions and the required header file to use these functions is <math.h>

Trignometric functions

MethodDescription
cos(x)It computes the cosine of x.
sin(x)It computes the sine of x.
tan(x)It computes the tangent of x.
acos(x)It finds the inverse cosine of x.
asin(x)It finds the inverse sine of x.
atan(x)It finds the inverse tangent of x.
atan2(x,y)It finds the inverse tangent of a coordinate x and y.

Hyperbolic functions

MethodDescription
cosh(x)It computes the hyperbolic cosine of x.
sinh(x)It computes the hyperbolic sine of x.
tanh(x)It computes the hyperbolic tangent of x.
acosh(x)It finds the arc hyperbolic cosine of x.
asinh(x)It finds the arc hyperbolic sine of x.
atanh(x)It finds the arc hyperbolic tangent of x.

Exponential functions

MethodDescription
exp(x)It computes the exponential e raised to the power x.
frexp(value_type x,int* exp)It breaks a number into significand and 2 raised to the power exponent.
Idexp(float x, int e)It computes the product of x and 2 raised to the power e.
log(x)It computes the natural logarithm of x.
log10(x)It computes the common logarithm of x.
modf()It breaks a number into an integer and fractional part.
exp2(x)It computes the base 2 exponential of x.
expm1(x)It computes the exponential raised to the power x minus one.
log1p(x)It computes the natural logarithm of x plus one.
log2(x)It computes the base 2 logarithm of x.
logb(x)It computes the logarithm of x.
scalbn( x, n)It computes the product of x and FLT_RADX raised to the power n.
scalbln( x, n)It computes the product of x and FLT_RADX raised to the power n.
ilogb(x)It returns the exponent part of x.

Floating point manipulation functions

MethodDescription
copysign(x,y)It returns the magnitude of x with the sign of y.
nextafter(x,y)It represents the next representable value of x in the direction of y.
nexttoward(x,y)It represents the next representable value of x in the direction of y.

Maximum,Minimum and Difference functions

MethodDescription
fdim(x,y)It calculates the positive difference between x and y.
fmax(x,y)It returns the larger number among two numbers x and y.
fmin()It returns the smaller number among two numbers x and y .

Power functions

MethodDescription
pow(x,y)It computes x raised to the power y.
sqrt(x)It computes the square root of x.
cbrt(x)It computes the cube root of x.
hypot(x,y)It finds the hypotenuse of a right angled triangle.

Nearest integer operations

MethodDescription
ceil(x)It rounds up the value of x.
floor(x)It rounds down the value of x.
round(x)It rounds off the value of x.
lround(x)It rounds off the value of x and cast to long integer.
llround(x)It rounds off the value of x and cast to long long integer.
fmod(n,d)It computes the remainder of division n/d.
trunc(x)It rounds off the value x towards zero.
rint(x)It rounds off the value of x using rounding mode.
lrint(x)It rounds off the value of x using rounding mode and cast to long integer.
llrint(x)It rounds off the value x and cast to long long integer.
nearbyint(x)It rounds off the value x to a nearby integral value.
remainder(n,d)It computes the remainder of n/d.
remquo()It computes remainder and quotient both.

Other functions

MethodDescription
fabs(x)It computes the absolute value of x.
abs(x)It computes the absolute value of x.
fma(x,y,z)It computes the expression x*y+z.

Macro functions

MethodDescription
fpclassify(x)It returns the value of type that matches one of the macro constants.
isfinite(x)It checks whether x is finite or not.
isinf()It checks whether x is infinite or not.
isnan()It checks whether x is nan or not.
isnormal(x)It checks whether x is normal or not.
signbit(x)It checks whether the sign of x is negative or not.

Comparison macro functions

MethodDescription
isgreater(x,y)It determines whether x is greater than y or not.
isgreaterequal(x,y)It determines whether x is greater than or equal to y or not.
less(x,y)It determines whether x is less than y or not.
islessequal(x,y)It determines whether x is less than or equal to y.
islessgreater(x,y)It determines whether x is less or greater than y or not.
isunordered(x,y)It checks whether x can be meaningfully compared or not.

Error and gamma functions

MethodDescription
erf(x)It computes the error function value of x.
erfc(x)It computes the complementary error function value of x.
tgamma(x)It computes the gamma function value of x.
lgamma(x)It computes the logarithm of a gamma function of x.

Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&