Inline Function BY Junaid Ali Siddiqui
Inline Function
Functions are used to avoid code duplication. At each call (to a function), control is passed to the function at a specified address in the memory. If the same function is called several times, each time the control is passed to the function. Due to this passing of control, execution speed decreases. C++ provides a mechanism called ‘Inline Function’.
Continued…
Compiler copies the code of inline function in the calling function, i.e. Function body is inserted in place of function call during compilation. So transfer of control is avoided. Inline function are mostly used when the function is small. Execution performance is increased but inline function needs more memory.
Example inline int square(int j) { return (j*j); } void main() { clrscr(); int p=3,r; r=square(p); cout<<“r= ”<
Situation where inline Function may not work
The function should not be recursive. Function should not contain static variables. Function containing control structure statements, such as switch, if, for loop etc. The main() function can not work as inline.
Friend Function
Friend Function
The central idea of encapsulation and data hiding is that any non-member function has no access permission to the private data of the class. However, C++ allows a mechanism, in which a non-member function has access permission to the private member of the class. This can be done by declaring a non-member function friend to the class whose private data is to be accessed.
Continued…
Declaration is done in public or private section. A function can be declared as friend function in any number of calsses. These functions use objects as arguments.
Example class ac { int acno; float bal; Public: Void read() { cout<<“ Account No: “; cin>>acno; cout<<“\n Balance : “; cin>>bal; } Friend void show(ac); };
void show(ac a) { cout<<“Balance of A/C No.”<
Assignment
Write a program to exchange values b/w two classes. Use friend function. Write a program to declare three classes, declare integer array as data member in each class. Perform addition of two data member arrays into array of third class. Use Friend function. Send *.ccp files at
[email protected]
Have a good day!