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

Similar documents
PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

The C Programming Language course syllabus associate level

Calculating Area, Perimeter and Volume

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

Chapter 13 Storage classes

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

13 Classes & Objects with Constructors/Destructors

C++ INTERVIEW QUESTIONS

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Object Oriented Software Design II

Lecture 22: C Programming 4 Embedded Systems

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

The programming language C. sws1 1

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Revision Notes Adult Numeracy Level 2

Chapter 5 Functions. Introducing Functions

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

Computer Science 1 CSci 1100 Lecture 3 Python Functions

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Sources: On the Web: Slides will be available on:

Introduction to Data Structures

Keil C51 Cross Compiler

C++FA 5.1 PRACTICE MID-TERM EXAM

(Eng. Hayam Reda Seireg) Sheet Java

Comp151. Definitions & Declarations

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Introduction to Java. CS 3: Computer Programming in Java

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Moving from CS 61A Scheme to CS 61B Java

Chapter One Introduction to Programming

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Java Interview Questions and Answers

Java Basics: Data Types, Variables, and Loops

COMPUTER SCIENCE 1999 (Delhi Board)

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Java CPD (I) Frans Coenen Department of Computer Science

Habanero Extreme Scale Software Research Project

Pseudo code Tutorial and Exercises Teacher s Version

Example of a Java program

Introduction to Java

Variables, Constants, and Data Types

Chapter 5 Names, Bindings, Type Checking, and Scopes

Subject Name: Object Oriented Programming in C++ Subject Code:

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

SURFACE AREAS AND VOLUMES

C++ Language Tutorial

Basic Object-Oriented Programming in Java

C++FA 3.1 OPTIMIZING C++

Chapter 2 Introduction to Java programming

Programming Language Features (cont.) CMSC 330: Organization of Programming Languages. Parameter Passing in OCaml. Call-by-Value

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Course notes Standard C++ programming

I PUC - Computer Science. Practical s Syllabus. Contents

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Compiler Construction

Curriculum Map. Discipline: Computer Science Course: C++

Data Structures using OOP C++ Lecture 1

An Incomplete C++ Primer. University of Wyoming MA 5310

While Loop. 6. Iteration

10CS35: Data Structures Using C

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Application Note C++ Debugging

MXwendler Javascript Interface Description Version 2.3

C++ Overloading, Constructors, Assignment operator

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

CS 106 Introduction to Computer Science I

Informatica e Sistemi in Tempo Reale

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Lecture 5: Java Fundamentals III

Object Oriented Software Design II

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Programming Language Rankings. Lecture 15: Type Inference, polymorphism & Type Classes. Top Combined. Tiobe Index. CSC 131! Fall, 2014!

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Java Crash Course Part I

Geometry - Calculating Area and Perimeter

7 Literal Equations and

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Syllabus OBJECT ORIENTED PROGRAMMING C++

VB.NET Programming Fundamentals

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Syllabus for Computer Science. Proposed scheme for B.Sc Programme under Choice Based Credit System

Semester Review. CSC 301, Fall 2015

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

El Dorado Union High School District Educational Services

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Transcription:

Inline functions 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 Square of 5 = 25 inlineint square(int x) Square of 10 = 100 return(x*x); Square of 15 = 225 Square of 20 = 400 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 inlineint cube(int x) return(x*x*x); int n; cout<<"enter the number: "; cin>>n; cout<<"cube of "<<n<<" = "<<cube(n); Enter the number: 10 Cube of 10 = 1000 Enter the number: -5 Cube of -5 = -125

To convert the temperature from Celsius to Fahrenheit using inline function (F=C*1.8+32) inline float ctof(float c) return(c*1.8+32); 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) inline float ctof(float c) return(c*1.8+32); inline float kmtom(float k) return(k*0.62137); floatcelsius; float kms; Friend functions 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"; 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 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

Example 8.3: class base nt val1, val2; 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 int a,b; 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

object.setvalue(34, 56); cout<<"sum of 34 and 56 is "<<add(object)<<endl; return 0; To find the factorial of a number class factorial int n, fact; 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); factorial F; F.read(); cout<<"factorial = "<<facto(f); To find the total marks of four subjects of a student: Enter the number: 5 Factorial = 120 #include <iostream.h> class addition int m1, m2, m3, m4; 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() Total marks: 200 addition s1; s1.setvalue(50, 50, 50, 50); cout<< "Total marks: "<<total(s1)<<endl; return 0;

To find the total salary of husband and wife: #include <iostream.h> #include<iomanip.h> class wife; class husband char name[10]; int voidgetdata() salary; 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 char name[10]; int salary; 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); 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<iomanip.h> class exchange int a, b; 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

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; 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<iomanip.h> class exchange int a, b; 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; 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

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: Note: 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. 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<conio.h> classfunoverload

int volume(ints) returns*s*s; //Volume of Cubes 3 double volume(double r, double h) // Volume of Cone return ((1/3)*3.143*r*r*h); // 1/3*πr 2 h π = 22 7 double volume(double r, int h) // Volume of Cylinder return (3.143*r*r*h); // πr 2 h double volume(double l, double b, double h) //Volume of Cuboid return (l*b*h); Volume of the Cube: 1000 ; Volume of the Cone: 12.4344 int main() Volume of the Cylinder: 37.68 Volume of the Cuboid: 210 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 int a, b; char s1[10], s2[10]; 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); Enter two numbers: 10 20 Enter the first string: Raj Enter the second string: appa Concatenated string: Rajappa sum: 30

overload f; f.fun(); To find the area of square, rectangle and triangle using function overloading #include<process.h> #include<iomanip.h> classfunoverload double area(double a) return a*a; double area(double l, double b) Enter the number of sides (1, 2 and 3): 1 return (l*b); Enter the side: 4.5 Area of the square = 20.25 double area(double a, double b, double c) Enter the number of sides (1, 2 and 3): 2 floats=(a+b+c)/2.0; Enter two sides: 4.5 2.75 return(sqrt(s*(s-a)*(s-b)*(s-c))); Area of the rectangle = 12.375 ; clrscr(); double x, y, z; intans; funoverload f; 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 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();

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. *****