FUNCTIONS

advertisement

FUNCTIONS

Learning Objectives

• Constant Parameters, Constant Return Types

• Friend Functions and Friend Classes.

• Static Class Members.

• Composition

• Dynamic Memory Management

• Arrays of objects.

Functions

– Functions make the program easier to read

– A function can be useful in many places in a program

– Ease testing, distribution of labor, and maintenance

– Keep functions small

• Easier to understand, specify, and debug

Functions

• To construct programs modularly

• Mechanisms used to pass information between fuctions

• Simulation techniques using random number generation

• Identifiers limited to specific regions of programs

• Write and use functions that call themselves.

Pass By Value void f ()

{ int i = 7; b (i);

} void b (int j)

{ j = 3;

}

Pass By Reference void f ()

{

} void b (int & j)

{ j = 3;

} int i = 7; b (i);

7 local variable i (stays 7)

Think of this as declaration with initialization, along the lines of: int j = what b was passed;

7 → 3 parameter variable j (initialized with the value passed to b, and then is assigned the value 3) again declaration with initialization int & j = what b was passed;

7 → 3

7 → 3 argument variable j local variable i j is initialized to refer to the variable that was passed to baz: when j is assigned 3, the passed variable is assigned 3.

Comparing Call by Value, Call by Reference with Pointers and Call by Reference with References

#include <iostream>

} using namespace std; int sqrByValue(int); void sqrByPointer(int *); void sqrByRef(int &); int main() { int x = 2, y = 3, z = 4,w; cout << "x = " << x << " before sqrByVal\n"; w=sqrByValue(x); cout<< "Value returned by sqrByVal: "<< w << "\nx = " << x << " after sqrByVal\n\n"; cout << "y = " << y << " before sqrByPointer\n"; sqrByPointer(&y); cout << "y = " << y << " after sqrByPointer\n\n"; cout << "z = " << z << " before sqrByRef\n"; sqrByRef(z); cout << "z = " << z << " after sqrByRef\n"; return 0;

6

int sqrByValue(int a)

{ cout<< "the value passed to function is: " << a<<endl; return a *= a;// caller's argument not modified

}

} void sqrByPointer(int *bPtr)

{ cout<<"the value passed to function is: "<< bPtr<< endl;

*bPtr *= *bPtr; // caller's argument modified void sqrByRef(int &cRef)

{ cout<<"the value passed is:"<< cRef<<endl; cRef *= cRef; // caller's argument modified

}

Output: x = 2 before sqrByVal the value passed to function is: 2

Value returned by sqrByVal: 4 x = 2 after sqrByVal y = 3 before sqrByPointer the value passed to function is: 0x7fff6bb7afa4 y = 9 after sqrByPointer z = 4 before sqrByRef the value passed is:4 z = 16 after sqrByRef

Constant parameters

• All variables defined in function definitions are local variables

• A function’s parameters are also local variables of that function

• The function prototype is a declaration statement in the calling program

Type function-name (argument-list);

Example: float volume (int x, float y, float z);

• An argument to a function can be declared as const

Int strlen( const char *P);

Int length( const string &s);

The qualifier const tells the compiler that the function should not modify the argument. The compiler will generate an error when this condition is violated

.This type of declaration is significant only when we pass arguments by reference or pointers.

Constant return

• It is used to mark the end of a function execution and to transfer the control back to the calling function.

• It can also return a value of an expression to the calling function.

• Many operating systems test the return value (called exit value) to determine if there is any problem.

• The normal convention is that an exit value of zero means the program ran successfully, while a non zero value means there was a problem. The explicit use of a return(0) statement will indicate that the program was successfully executed.

Return(expression);

Cont…

}

{

• Example:

Int & max(int& x,int& y) if (x>y) return x; else return y;

Example : rectCalc2.cpp

#include <iostream> using namespace std; void rect_calc(const double l, const double w, double & area, double & perim);

{ int main() double rectArea(0.0), rectPerim(0.0), rectLength(2.0), rectWidth(3.0); rect_calc(rectLength, rectWidth, rectArea, rectPerim); cout << "Area: " << rectArea << endl; cout << "Perimeter: " << rectPerim << endl;

}

// function definition

}

{ void rect_calc(const double l, const double w, double & area, double & perim) area = l * w; perim = 2 * (l + w);

OUTPUT:

Area: 6

Perimeter: 10

return types

• Long double 10 3.4E -4932 to 1.1E + 4932

• Double 8 1.7E -308 TO 1.7E + 308

• Float 4 3.4E -38 to 3.4E+38

• Unsigned long int 4 0 to 4294967295

• Long int

• Unsigned int

4 - 2147483648 to 2147483647

2 0 to 65535

• Int 2 -32768 to 32767

• Unsigned short int 2 0 to 65535

• Char 1 -128 to 127

• Bool 1 false becomes 0, true becomes 1

Library function types

• Ceil (x) ceil(9.2) is 10.0, ceil(-9.8) is -9.0

• Cos(x) cos(0.0) is 1.0

• Exp(x) - exp(1.0) is 2.718282

• Fabs(x) fabs (5.1) is 5.1

• Floor(x) floor(9.2) is 9.0

• Fmod (x,y) fmod (2.6,1.2 ) is 0.2

• Log (x) log(2.718282) is 1.0

• Log 10(x) log10(10.0) is 1.0

• Pow(x,y) pow(2,7) is 128

• Sin(x) sin(0.0) is 0

• Sqrt(x) sqrt(9.0)is 3.0

• Tan (x) tan(0.0) is 0

Friend function and Friend classes

• The function declared with the keyword friend are known as friend functions.

• A function can be declared as a friend in any number of classes.

• A friend function possesses certain special characteristics:

1.

It is not in the scope of the class to which it has been declared as friend.

2.

Since it is not in the scope of the class, it cannot be called using the object of that class. It can be invoked like a normal function without the help of any object

3.

Unlike member functions, it cannot access the member names directly and has to use an object name and dot membership operator with each member name.(e.g. ASHA.X)or (e.g. a.x)

4.

It can be declared either in the public or the private part of a class without affecting its meaning

5.

Usually, it has the objects as arguments. It is often used in operator overloading

6.

Member functions of one class can be friend functions of another class.

Cont…

• A friend function of a class is defined outside that class’s scope, to access the non-public members of the class.

• Standalone functions or entire classes may be declared to be friends of another class.

example

• # include <iostream.h>

• Class sample

{ int a; int b; public: void setvalue() [a=25; b=40;] friend float mean (sample s); // Friend declared

};

{ float mean (sample s) return float (s.a + s.b) /2.0;

{

} main() sample x ; // object X

X.setvalue() ; cout << “ mean value = “ << mean(x) << “\n” ;

}

The output will be 32.5

Friends of Classes

• Friend function : a function that is not a member of a class, but has access to private members of the class

• A friend function can be 1) a stand-alone function or 2) a member function of another class

• It is declared a friend of a class with the friend keyword in the function prototype

Friend Function Declarations:

1) Friend function may be a stand-alone function: class aClass

{ private: int x;

}; friend void fSet(aClass &c, int a); void fSet(aClass &c, int a)

{ c.x = a;

}

2) Friend function may be a member of another class: class aClass

{ private: int x; friend void OtherClass::fSet(aClass &c, int a);

}; class OtherClass

{ public: void fSet(aClass &c, int a)

{ c.x = a; }

};

3) An entire class can be declared a friend of a class: class aClass

{private: int x;

}; friend class frClass; class frClass

{public:

}; void fSet(aClass &c,int a){c.x = a;} int fGet(aClass c){return c.x;}

• If frClass is a friend of aClass , then all member functions of frClass have unrestricted access to all members of aClass , including the private members.

• In general, restrict the property of

Friendship to only those functions that must have access to the private members of a class.

Static Class Members

• Important exception to the rule that each object of a class has its own copy of all the data members of the class.

• In certain cases, only one of a variable should be shared by all objects of a class.

• A static data member is used for these reasons following properties:

• A static function can have access to only other static members (function or variables) declared in the same class.

• A static member function can be called using the class name (instead of its objects) as follows:

Example:

}

{

Int Employee::getcount() return count; class-name::function-name;

Cont…

• Each object of a class has its own copy of all the data members of the class.

• In some cases ,only one copy of a variable should be shared by all objects of a class.

• A static class variable represents “class-wide” information (i.e, a property of the class, not a property of a specific object of the class)

• The declaration of a static member begins with keyword static

CONT..

• Example

Class Employee{

Public: employee(const char*, const char*) ;

~Employee (); const char *getfirstname () const; const char *getlastname () const;

//static member function

Static int getcount();

Private: char *first name; char *last name;

// static data member static int count;

} ; //end class Employee

Static Members

• Static variables:

- Shared by all objects of the class

Like a “global variable” among objects of the class

• Static member functions:

- Can be used to access static member variables

- Can be called before any objects are created

Static Member Variables

1) Must be declared in class with keyword static : class IntVal

{ public:

IntVal(int val = 0)

{ value = val; valCount++ } int getVal(); void setVal(int); private: int value; static int valCount;

};

Static Member Variables

2) Must be defined outside of the class: class IntVal

{

//In-class declaration static int valCount;

//Other members not shown

};

//Definition outside of class int IntVal::valCount = 0;

3) Can be accessed or modified by any object of the class:

Modifications by one object are visible to all objects of the class :

IntVal val1, val2; valCount

2 val1 val2

Static Member Functions

1)Declared with static before return type:

}; class IntVal

{ public: static int getValCount()

{ return valCount; } private: int value; static int valCount;

2) Can be called independently of class objects, through the class name: cout << IntVal::getValCount();

3) Can be called before any objects of the class have been created

4) Used mostly to manipulate static member variables of the class

composition

• In real-life, complex objects are often built from smaller, simpler objects. For example, a car is built using a metal frame, an engine, some tires, a transmission, a steering wheel, and a large number of other parts. A personal computer is built from a CPU, a motherboard, some memory, etc… Even you are built from smaller parts: you have a head, a body, two legs, arms, and so on. This process of building complex objects from simpler ones is called composition(also known as object composition).

• More specifically, composition is used for objects that have a has-a relationship to each other. A car has-a metal frame, has-an engine, and has-a transmission. A personal computer has-a CPU, a motherboard, and other components. You have-a head, a body, some limbs.

Composition

• A class has objects of other classes as members

• An alarm clock object needs to know when its supposed to sound its alarm ,so include a time object as a member of alarmclock as a class

• The most common form of software reusbility is composition, in which a class has objects of other classes as members

Cont…

• So far, all of the classes we have used in our examples have had member variables that are built-in data types (eg. int, double). While this is generally sufficient for designing and implementing small, simple classes, it quickly becomes burdensome for more complex classes, especially those built from many sub-parts. In order to facilitate the building of complex classes from simpler ones, C++ allows us to do object composition in a very simple way — by using classes as member variables in other classes.

Cont…

• Example:

• If we were designing a personal computer class, we might do it like this (assuming we’d already written a CPU, Motherboard, and RAM class):

Dynamic memory management

• C++ enables programmers to control the allocation and deallocation of memory in a program for any built-in or user-defined type.

• It is performed with operators new and delete

• Dynamic memory management should include standard header <new>

Ex:

Time *timeptr;

Timeptr = new Time;

Cont…

• Operator new creates an object of the proper size for type TIME.

• Calls the default constructor for the object and returns a pointer of the type specified to the right of operator new --- (Time)

• New can be used to dynamically allocate any primitive type(such as INT OR DOUBLE) or class type.

• If new is unable to find space in memory for the object, it indicates that an error occurred by “throwing “ an

“exception”

Cont…

• To destroy a dynamically allocated object and free the space for the object , use the delete operator delete timeptr;

• The preceding statement first calls the destructor for the object to which timeptr points, then deallocates the memory associated with the object

The following example first allocates the memory dynamically to pvalue, then deallocates the memory associated with the pointer variable.

}

#include <iostream>

//#include<new> using namespace std;

{ int main () double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address if (pvalue == NULL) cout << "Error: memory could not be allocated"; else { cout << "Value of pvalue : " << *pvalue << endl; delete pvalue; // free up the memory.

} return 0;

Arrays of object

• Array data structure is fixed in size once its created.

• The size is specified with a constant at compile time.

• Useful to determine the size of an array dynamically at execution time and then create the array.

• C++ enables you to control the allocation and deallocation of memory in a program for objects and for arrays of any built-in of user defined type

• Its is performed with the operators new and delete.

• Use new operator to dynamically allocate of memory required to hold an object or array at execution time.

• Once the memory

Cont…

• Array can be any data type including Struct

• Arrays can have variables of type class , this variables are called arrays of objects

• Class employee

{ char name[30]; float age; public: void getdata(void); void putdata(void);

};

Cont..

• The identifier employee is a user-defined data type and can be used to create objects that relate to different categories of the employees.

• Example:

Employee manager[3]; // array of manager

Employee foreman[15]; // array of foreman

Employee worker[75];// array of worker

Cont..

• The array manager contains three objects(managers),namely, manager[0],manager[1] and manager[2] of type employee class.

manager(0) name age name manager(1)

` age name age manager(2)

Cont..

• Similarly the foreman array contains 15 objects

(foreman) and the worker array contains 75 object (workers)

• Since an array of objects behaves like any other array, can use the usual array –accessing methods to access individual elements and then the dot member operator to access the member functions.

Example

Manager(i).putdata();

Cont…

• will display the data of the ith element of array manager.

• This statement requests the object manager(i) to invoke the member function putdata().

• An array of objects is stored inside the memory in the same way as a multi-dimensional array.

• The space for data items of the objects is created.

• Member functions are stored separately and will be used by all the objects.

void main(){

Details det[MAX]; int n=0; char ans; do{ cout << "Enter the Employee Number::" << n+1; det[n++].getname; cout << "Enter another (y/n)?: " ; cin >> ans;

} while ( ans != 'n' ); for (int j=0; j<n; j++){ cout << "\nEmployee Number is:: " << j+1; det[j].putname( );

} }

Result:Enter the Employee Number:: 1

Enter the Salary:20

Enter the roll:30

Enter another (y/n)?: y

Enter the Employee Number:: 2

Enter the Salary:20

Enter the roll:30

Enter another (y/n)?: n

In the above example an array of object

"det" is defined using the user defined data type "Details". The class element

"getname()" is used to get the input that is stored in this array of objects and putname() is used to display the information.

Download