49
Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 1 Haresh Jaiswal Rising Technologies, Jalna.

02. functions & introduction to class

Embed Size (px)

Citation preview

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 1

Haresh Jaiswal

Rising Technologies, Jalna.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 2

Function Overview Function plays an important role in Programdevelopment.

Dividing program logic in functions/sub-programs is oneof the major principles of top-down, structuredprogramming.

Another advantage of using function is that it is possibleto reduce the size of program by calling & using them atmultiple times in the program.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 3

Function Overviewvoid show(); // declaration/prototype

main()

{

...

show(); // function call

...

}

void show() // function definition

{

... // function body

...

}

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 4

Functions in C++ C++ has added many new features to functions to makethem more reliable and flexible.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 5

What is new in C++ Functions Call by Reference using Reference Variable.

Return by Reference.

Inline Functions.

Default Arguments.

Const Arguments.

Function Overloading.

Friend & Virtual Functions.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 6

Call By Reference vs. Call By value In traditional C, a function call passes arguments by itsvalue. The called function creates new set of variablesand copies the value of arguments into them.

The called function does not have access to the actualvariables in the calling program and can only work onthe copies of values.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 7

Example of Call By Value.int sum(int, int);

main()

{

int a = 4, b = 3, c;

c = sum(a, b);

cout << “Add is : “ << c;

}

int sum(int x, int y)

{

int addition = x + y;

return addition;

}

Add is : 7

Output

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 8

Call By Reference vs. Call By value This mechanism is fine if the function does not need tomodify the values of the original variables in the callingprogram.

But there may arise some situations where we wouldlike to change the values of variables in the callingprogram.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 9

Call By Reference. Provisions of the reference variable in c++ permits us topass parameters to the function by reference.

When we pass arguments by reference, the ‘formal’arguments in the called function became aliases of‘actual’ arguments in the calling program.

This means when the called function is working with itsown arguments, it is actually working on the originalvariables of calling function.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 10

Call By Reference.void swap(int&, int&);

main()

{

int a = 10, b = 20;

swap(a, b);

cout << “A : “ << a << endl << “B : “ << b;

}

// x and y are references

void swap(int &x, int &y)

{

int temp = x;

x = y;

y = temp;

}

A : 20

B : 10

Output

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 11

Call By Reference. When the function call like

swap(a, b);

executes, then the following initialization occurs.

int &x = a;

int &y = b;

Any changes made to variable ‘x’ and ‘y’ in swap functionwill reflect to variables ‘a’ and ‘b’ of main, because ‘x’ and‘y’ are simply aliases of ‘a’ and ‘b’

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 12

Call By Reference using pointers.void swap(int*, int*);

main()

{

int a = 10, b = 20;

swap(&a, &b);

cout << “A : “ << a << endl << “B : “ << b;

}

// x and y are now pointers

void swap(int *x, int *y)

{

int temp = *x;

*x = *y;

*y = temp;

}

A : 20

B : 10

Output

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 13

Return By Reference. In C++, not only you can pass arguments by reference but

also you can return a reference from a function.

When a function returns a reference, it returns an implicitpointer to its return value. This way, a function can beused on the left hand side of an assignment operator.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 14

Return By Reference.int n; // a global variable

int& test(); // function prototype

main()

{

test() = 5;

cout << “N : “ << n;

}

int& test()

{

return n;

}

N : 5

Output

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 15

Return By Reference : Explanation

In this example, the return type of function test() is int&.Hence this function returns a reference.

The return statement is return n; but unlike return byvalue. This statement doesn't return value of n, instead itreturns variable n itself.

int& test()

{

return n;

}

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 16

Return By Reference : Explanation When the function is called from main the yield of the

function call is variable n itself, so when the followingstatement in main executes it assigns 5 to variable n

test() = 5;

In simple words, variable n is assigned at the left handside of statement test() = 5;

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 17

Points to keep in mind. You cannot return a local variable (which is non-static)

from a function which returns a reference.

Following piece of code will generate a compile error.

int& test()

{

int n; // n is local variable

return n; // compile error

}

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 18

Points to keep in mind. But if I change int n; to static int n; then

Following piece of code will be successfully compiled andrun perfectly.

int& test()

{

static int n; // n is now a static

// local variable

return n; // perfectly fine

}

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 19

Points to keep in mind. Ordinary function returns value but this function doesn't.

Hence, you can't return constant from this function.

Following piece of code will generate a compile error.

int& test()

{

return 2; // compile error

}

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 20

Return By Reference. A function can also return a reference.

int& max(int &x, int &y)

{

if(x>y)

return x;

else

return y;

}

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 21

Return By Reference. Since the return type of max() is int &, thefunction returns reference to x or y.

The function call such as max(a, b) will return areference either to a or b depending on theirvalues. That means the function call canappear on the left hand side of an assignmentoperator.

max(a, b) = 0;

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 22

Inline Functions Every time a function get called it takes a lot of extratime in executing a series of instructions for tasks, suchas jumping to the function, saving registers, pushingarguments into the stack, and returning to the callingfunction.

solution to solve this problem is to use inline functions.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 23

Inline Functions An Inline function is a function that is expanded in linewhen it is invoked.

The compiler replaces the function call with thecorresponding function code.

Inline expansion makes program run faster because theoverhead of a function call and return is eliminated.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 24

Inline Functionsinline double cube(double n)

{

return (n*n*n);

}

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 25

Inline Functions Remember that inline keyword sends a request, not acommand, to the compiler.

The compiler may ignore this request if the functiondefinition is too long or too complicated.

In such cases compiler will compile the function as anormal function.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 26

Inline Functions Some of the situations where inline expansion may notwork.

If function contains a loop, switch or goto statement.

If function contains static variables.

If function is a recursive function.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 27

Default arguments C++ allows us to call a function without specifying all

its arguments. In such cases, the function assigns adefault value to the parameters.

Default values are specified when the function isdeclared.

The compiler looks at the prototype to see how manyarguments a function uses and alerts the program fordefault values.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 28

Default arguments Consider the following prototype.

float interest(float amt, int period, float irate=7.2);

The default value is specified in a manner similar to avariable initialization.

Above prototype declares a default value of 7.2 to theargument irate.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 29

Default arguments Consider the following prototype.

float interest(float amt, int period, float irate=7.2);

A function call like

x = interest(5000, 8); // one argument missing

Passes the value 5000 to amt, and 8 to period and let thefunction use default value of 7.2 for irate.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 30

Default arguments Consider the following prototype.

float interest(float amt, int period, float irate=7.2);

A function call like

x = interest(5000, 8, 6.3); //no missing argument

Passes the value 5000 to amt, and 8 to period, and 6.3 forirate.

Passes an explicit value of 6.3 to irate

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 31

Default arguments One important point to note is that the only trailing

arguments can have default values.

We must add defaults from right to left.

We cannot provide a default value to a particularargument in the middle of an argument list.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 32

Default arguments Some Examples :

int mul(int i, int j=5, int k=10); // legal

int mul(int i, int j=5, int k); // illegal

int mul(int i=2, int j, int k=2); // illegal

int mul(int i=5, int j=2, int k=4); // legal

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 33

Default arguments Default arguments are useful in situations where some

arguments always have the same value.

For example bank interest may retain same for allcustomers for a particular period of deposits.

It also provides a greater flexibility to the programmers bysending all arguments explicitly.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 34

const arguments In C++, an argument to a function can be declared as

const,

int length(const char p[]);

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 35

const arguments The qualifier const tells the compiler that the

function should not modify the argument.

The compiler will generate an error when thiscondition is violated. This type of declaration issignificant only when we pass arguments byreference or pointers.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 36

Introduction to Class Like structures in C, class is a user defined data type inC++.

A Class is extension of the idea of structures used in C.

It is a new way of creating and implementing a userdefined data type.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 37

Structures Revised Structures in C provides a method of packing differenttype of data together.

A structure is a convenient tool for handling a group oflogically related data items.

Once the structure type has been defined, we cancreate any number of variables of that type.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 38

Structures Revised Consider following structure.

struct student

{

int rollno;

char name[25];

int marks;

};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 39

Structures Revised Consider following Declaration.

struct student a;

‘a’ is a variable of type ‘student’ and

contains 3 member variables, which

can be accessed by using ‘.’ operator.

a.rollno = 15;

strcpy(a.name, “Aditya”);

a.marks = 435;

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 40

Limitations of C Structures C structures do not provide the concept of datahiding.

Structure members can be directly accessed by thestructure variables by any function in their scope.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 41

Extensions to Structures in C++ C++ supports all features of structures as defined in C,in addition C++ has expanded its capabilities to suit itsOOP philosophy.

It attempts to bring the user-defined types as close aspossible to built in data types, and also provides afacility to hide the data which is the major principle ofOOP.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 42

Extensions to Structures in C++ In C++ a structure can contain variables and functionsboth as its member.

It can also declare some of its members as ‘private’ sothat they cannot be accessed directly by the externalfunctions.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 43

Extensions to Structures in C++ In C++, the structure names are stand alone and canbe used like any other type names.

In other words the keyword ‘struct’ can be omittedfrom the declaration of the structure variables.

For example.

student a; // in c++

struct student a; // in c

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 44

Introduction to Class C++ incorporates all of these extensions inanother user defined data type ‘class’.

There is a very little syntactical differencebetween structure and classes in c++.

The only difference is that by default themembers of a class are private, while, by default,the members of a structure are public.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 45

Specifying a Class A class is a way of binding data and its associatedfunctions together, it allows the data (andfunctions) to be hidden from external world, ifnecessary.

While defining a class we are creating a newabstract data type, that can be treated like anyother built in data type.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 46

Specifying a Class Generally a class specifications has two parts.

Class declaration.

Class function definitions.

The class declaration describes the type and thescope of its members.

The class function definitions describes how theclass functions are implemented.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 47

General form of a Classclass class_name

{

private: // optional

variable declarations;

function declarations;

public:

variable declarations;

function declarations;

};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 48

General form of a Class The functions and variables declared in a class

are called as class members.

The class members declared as private can beaccessed only within the class, and themembers declared as public can be accessedfrom outside of the class also.

The variables declared inside a class are calledas data members, and the functions are calledas member functions.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 49

Public Area

Data

Functions

General form of a ClassClass

Entry not allowed for

outside world

X

Entry allowed for

outside world

Private Area

Data

Functions