Functions. If the inline function is called frequently, the size of the executable file increases and requires more memory.

10 

Loading....

Loading....

Loading....

Loading....

Loading....

Full text

(1)

Functions

Inline functions

 Member functions can be defined either inside or outside the class definition.A member function defined inside the class is called as an inline function.

 Inline functions are defined inside the class before other functions of that class.  The definition of inline functions begin with the keyword inline.

 Inline functions are small and simple.

 The compiler replaces the function call statement with the actual code.  Inline function run faster than normal functions.

 Function defined outside the class can be made inline including the keyword inline Advantages

 Inline functions are small in size and compact.

 Inline functions are executed faster than other functions.  Efficient code can be generated.

 Readability of the program is increased.

Disadvantage: If the inline function is called frequently, the size of the executable file increases and requires more memory.

Note:Inline functions do not work if:

 the definition is long and complicated.

 function code contains looping statements, switch or goto statements.  there are recursive calls

#include<iostream.h> inlineint square(int x) { return(x*x); } void main() { cout<<"Square of 5 = "<<square(5)<<endl; cout<<"Square of 10 = "<<square(10)<<endl; cout<<"Square of 15 = "<<square(15)<<endl; cout<<"Square of 20 = "<<square(20)<<endl; }

Program to find the cube of a number using inline function

#include<iostream.h> inlineint cube(int x) { return(x*x*x); } void main() { int n;

cout<<"Enter the number: "; cin>>n; cout<<"Cube of "<<n<<" = "<<cube(n); } Square of 5 = 25 Square of 10 = 100 Square of 15 = 225 Square of 20 = 400

Enter the number: 10 Cube of 10 = 1000 Enter the number: -5 Cube of -5 = -125

(2)

To convert the temperature from Celsius to Fahrenheit using inline function (F=C*1.8+32) #include<iostream.h>

inline float ctof(float c) { return(c*1.8+32); } void main() { floatCelsius;

cout<<"Enter the temperature in Celsius: "; cin>>Celsius;

cout<<Celsius<<"C = "<<ctof(Celsius)<<"F"; }

To convert the distance in kilometers to miles using inline function (1KM = 0.62137miles)

#include<iostream.h>

inline float ctof(float c) {

return(c*1.8+32); }

inline float kmtom(float k) { return(k*0.62137); } void main() { floatCelsius; float kms;

cout<<"Enter the temperature in Celsius: "; cin>>Celsius;

cout<<Celsius<<"C = "<<ctof(Celsius)<<"F"<<endl; cout<<"Enter the distance in kilometers: "; cin>>kms;

cout<<kms<<"kms = "<<kmtom(kms)<<"miles"; }

Friend functions

 We have seen that private and protected members of a class cannot be accessed from outside the class in which they are declared.

 In other words, non-member function does not have access to the private data members of a class.

 But there could be a situation where two classes must share a common function. C++ allows the common function to be shared between the two classes by making the common function as a friend to both the classes, thereby allowing the function to have access to the private data of both of these classes.

 A friend function is a non-member function that is a friend of a class.

 The friend function is declared within a class with the prefix friend.But it should be defined outside the class like a normal function without the prefix friend. It can access public members like non-member functions.

 Syntax: class class_name

{

public:

friend void function1(void); };

Enter the temparature in Celcius: 27 27C = 80.6F

Enter the temperature in Celsius: 27 27C = 80.6F

Enter the distance in kilometers: 5.25 5.25kms = 3.26219miles

(3)

Example 8.3: class base { nt val1, val2; public: voidgetdata() {

cout<<“Enter two values:”; cin>>val1>>val2;

}

friend float mean(base ob); };

float mean(base ob) {

return float(ob.val1+ob.val2)/2; }

In the above example,mean() is declared as friend function that computes mean value of two numbers input using getdata() function.

 A friend function although not a member function, has full access right to the private and protected members of the class.

 A friend function cannot be called using the object of that class. It can be invoked like any normal function.

 friend function is declared by the class that is granting access. The frienddeclaration can be placed anywhere inside the class definition. It is not affected by the access specifiers (public, private and protected.)

 Friend functions are normal external functions that are given special access privileges.

 It cannot access the data membersdirectly and has to use dot operator as objectname.membername(Here, dot is a direct membership access operator).

 The function is declared with keyword friend. But while defining friend function it does not use either keyword friend or :: operator.

To illustrate the use of friend function

#include <iostream.h> classmyclass { private: int a,b; public: voidsetvalue(int i, int j); friendint add(myclassobj); }; voidmyclass::setvalue(int i,int j) { a = i; b = j; } int add(myclassobj) { return (obj.a+obj.b); } int main() { myclass object; Sum of 34 and 56 is 90

(4)

object.setvalue(34, 56);

cout<<"Sum of 34 and 56 is "<<add(object)<<endl; return 0;

}

To find the factorial of a number

#include<iostream.h> class factorial { private: int n, fact; public: void read(); friendint facto(factorial x); }; void factorial::read() {

cout<<"Enter the number: "; cin>>n;

}

int facto(factorial x) {

x.fact = 1;

for(int i=1; i<=x.n; i++) x.fact =x.fact * i; return(x.fact); } void main() { factorial F; F.read(); cout<<"Factorial = "<<facto(F); }

To find the total marks of four subjects of a student:

#include <iostream.h> class addition { private: int m1, m2, m3, m4; public:

voidsetvalue(into, intp, intq, int r); friendint total(addition s);

};

void addition:: setvalue(into, intp, intq, int r) { m1 = o; m2 = p; m3 = q; m4 = r; } int total(addition s) { return (s.m1 + s.m2+s.m3 + s.m4); } int main() { addition s1; s1.setvalue(50, 50, 50, 50);

cout<< "Total marks: "<<total(s1)<<endl; return 0;

Total marks: 200 Enter the number: 5 Factorial = 120

(5)

}

To find the total salary of husband and wife:

#include <iostream.h> #include<iomanip.h> class wife; class husband { private: char name[10]; int salary; public: voidgetdata() {

cout<<"Enter the name of the husband: "; cin>>name;

cout<<"Enter the salary of the husband: "; cin>>salary; } friendinttotalsal(husband h, wife w); }; class wife { private: char name[10]; int salary; public: voidgetdata() {

cout<<"Enter the name of the wife: "; cin>>name;

cout<<"Enter the salary of the wife: "; cin>>salary; } friendinttotalsal(husband h, wife w); }; inttotalsal(husband h, wife w) {

cout<<"Husband salary: "<<h.salary<<endl; cout<<"Wife salary: "<<w.salary<<endl; return(h.salary + w.salary); } void main() { husbandhs; wife wf; hs.getdata(); wf.getdata();

cout<< "Total salary: "<<totalsal(hs, wf); }

C++ program to swap the values of two variables using friend functions (using reference variables).

#include<iostream.h> #include<iomanip.h> class exchange { private: int a, b; public: void read(); void print();

Enter the name of the husband: Rajappa Enter the salary of the husband: 5000 Enter the name of the wife: Shyla Enter the salary of the wife: 7500 Husband salary: 5000

Wife salary: 7500 Total salary: 12500

(6)

friend void swap(exchange &x); };

void exchange::read() {

cout<<"Enter two numbers: "; cin>>a>>b; } void exchange::print() { cout<<"a="<<a<<" b= "<<b<<endl; }

void swap(exchange &x) {

int temp = x.a; x.a = x.b; x.b = temp; } void main() { exchange E; E.read(); cout<<"Before swapping: "; E.print(); swap(E); cout<<"After swapping: "; E.print(); }

C++ program to swap the values of two variables using friend functions (using pointers).

#include<iostream.h> #include<iomanip.h> class exchange { private: int a, b; public: void read(); void print();

friend void swap(exchange *x); };

void exchange::read() {

cout<<"Enter two numbers: "; cin>>a>>b; } void exchange::print() { cout<<"a="<<a<<" b= "<<b<<endl; } void swap(exchange *x) {

int temp = x->a; x->a = x->b; x->b = temp; } void main() { exchange E; E.read(); cout<<"Before swapping: "; E.print(); swap(&E);

Enter two numbers: 10 20

Before swapping: a=10 b= 20 After swapping: a=20 b= 10

Enter two numbers: 10 20

Before swapping: a=10 b= 20 After swapping: a=20 b= 10

(7)

cout<<"After swapping: "; E.print();

}

Function overloading:

 Function overloading is the capability of using the name of the function to perform different tasks.

 A function is said to be overloaded when it has one name, but more than one distinct meaning and applications.

 Function overloading therefore is the process of defining same function name to carry out similar types of activities with various data items.

Advantages of function overloading or need for function overloading:  The code is executed faster.

 It is easier to understand the flow of information and debug.  Code maintenance is easy.

 Easier interface between programs and real world objects. Note:

 The main factor in function overloading is a functions’ argument list.

 C++ can distinguish overloaded functions by the number and type of arguments. If there are two functions having same name and different types of arguments or different number of arguments, then function overloading is invoked automatically by the compiler.

 Function overloading is also known as Compile time polymorphism. Example: int sum(int a, int b);

float sum(float p, float q);

The function sum() that takes two integer arguments is different from the function sum() that takes two float arguments. This is function overloading.

To overload a function, each overloaded function must be declared and defined separately.

Example: int product(int p, int q, int r); float product(float x,float y, float z); int product(int p, int q, int r) {

cout<<"product="<<p*q*r<<endl; }

float product(float x,float y,float z) {

cout<<"product="<<x*x*y*y*z*z<<endl; }

In this example the function product() is overloaded twice. The compiler automatically chooses the right type of function depending on the number of arguments. To compute volume of cone, cube cylinder and cuboid using function overloading.

#include<iostream.h> #include<conio.h> classfunoverload

(8)

{

public:

int volume(ints)

{

returns*s*s; //Volume of Cubes3

}

double volume(double r, double h) // Volume of Cone {

return ((1/3)*3.143*r*r*h); // 1/3*𝜋𝑟2h 𝜋 = 22 7 }

double volume(double r, int h) // Volume of Cylinder {

return (3.143*r*r*h); // 𝜋𝑟2h

}

double volume(double l, double b, double h) //Volume of Cuboid

{ return (l*b*h); } }; int main() { funoverload f1;

cout<<"Volume of the Cube: "<<f1.volume(10)<<endl; cout<<"Volume of the Cone: "<<f1.volume(2.0,3.0)<<endl; cout<<"Volume of the Cylinder: "<<f1.volume(2.0,3)endl;

cout<<"Volume of the Cuboid: "<<f1.volume(5.0,6.0,7.0)<<endl; return 0;

}

To find the sum and concatenation by function overloading

#include <iostream.h> #include<iomanip.h> #include<string.h> class overload { private: int a, b; char s1[10], s2[10]; public: void fun() {

cout<<"Enter two numbers: "; cin>>a>>b;

cout<<"Enter the first string: "; cin>>s1;

cout<<"Enter the second string: "; cin>>s2;

add(s1, s2);

cout<<"Concatenated string: "<<s1<<endl; cout<<"sum: "<<add(a,b);

}

void add(char *s1, char *s2); int add(int, int);

};

void overload::add(char *s1, char *s2) { strcat(s1, s2); } intoverload::add(int, int) { return(a+b);

Volume of the Cube: 1000 Volume of the Cone: 12.4344 Volume of the Cylinder: 37.68 Volume of the Cuboid: 210

Enter two numbers: 10 20 Enter the first string: Raj Enter the second string: appa Concatenated string: Rajappa sum: 30

(9)

Enter the number of sides (1, 2 and 3): 1 Enter the side: 4.5

Area of the square = 20.25

Enter the number of sides (1, 2 and 3): 2 Enter two sides: 4.5 2.75

Area of the rectangle = 12.375

Enter the number of sides (1, 2 and 3): 3 Enter three sides: 2 3.5 2.75

Area of a triangle = 2.74462

Enter the number of sides (1, 2 and 3): 5 Invalid input } void main() { overload f; f.fun(); }

To find the area of square, rectangle and triangle using function overloading

#include<process.h> #include<iostream.h> #include<iomanip.h> classfunoverload { public: double area(double a) { return a*a; }

double area(double l, double b) {

return (l*b); }

double area(double a, double b, double c) { floats=(a+b+c)/2.0; return(sqrt(s*(s-a)*(s-b)*(s-c))); } }; void main() { clrscr(); double x, y, z; intans; funoverload f;

cout<<"Enter the number of sides(1, 2 and 3): "; cin>>ans;

if (ans == 1) {

cout<<"Enter the side: "; cin>>x;

cout<<"Area of the square = "<<f.area(x)<<endl; }

else

if(ans == 2) {

cout<<"Enter two sides: "; cin>>x>>y;

cout<<"Area of the rectangle= "<<f.area(x,y)<<endl; }

else

if(ans == 3) {

cout<<"Enter three sides: "; cin>>x>>y>>z; cout<<setprecision(8); cout<<"Area of a triangle = " <<f.area(x,y,z)<<endl; } else cout<<"Invalid input"; getch(); }

(10)

One mark questions

1. What is meant by function overloading? 2. When is function overloading needed? 3. Write an advantage of function overloading. 4. Name one condition for overloading of functions. 5. What is an inline function?

6. Write one advantage of inline function.

7. The inline function is always converted to a code block. True/false 8. What is a friend function?

9. Write an example for friend function declaration. 10. Write one condition for using a friend function.

11. Can the key word friend be used while declaring a friend function?

12. Overloading a function means using different names to perform the same operations. True/false

Two marks questions

1. What is meant by overloading implements polymorphism?

2. Write example for definition and declaration of function overloading 3. What are the restrictions on overloaded functions?

4. What are inline functions? Give an example. 5. Write the advantages of inline functions.

6. Create an inline function to check whetherthe number is Prime or not.

7. When are friend functions used? Write syntax for declaration of friend function. 8. Write any two characteristics of friend function.

Three mark questions

1. Write any three reasons for function overloading. 2. What are the advantages of inline functions?

3. Write the advantages and disadvantages of inline functions. 4. When is it possible that an inline function may not work? 5. Write any three characteristics of friend function.

Five mark questions

1. Explain the need for function overloading.

2. Discuss overloaded functions with syntax and example. 3. Explain inline functions with syntax and example. 4. Explain friend functions and their characteristics.

Figure

Updating...

References

Updating...

Related subjects :