Anda di halaman 1dari 46

Functions

Objects as function arguments

There are two methods of passing the objects: pass by value and pass by reference.

When an object is passed by value, a copy of this object is passed to the function and any changes made to the object inside the function do not affect the object used to call the function.
On other hand, when the object is passed by reference, the called function works directly on the actual object used in the call. The pass by reference method is more efficient since it requires to pass only the address of the object and not the entire object.

Example:

// This program illustrates the passing of objects as arguments #include<iostream.h> class Complex { float real, imaginary ; public: Complex( ) { real = 0.0; imagnary = 0.0 ; } Complex(float r, float i) { real = r ; imaginary = i ; } void enter_data(void) { cout << "\n Enter the real number: " ; cin >> real ; cout << " Enter the imaginary number: " ; cin >> imaginary ; } void display_data(void) { if(imaginary >=0) cout << "\n\t The complex number is: " << real << "+" << imaginary << " i" << endl ; else cout << "\n\t The complex number is: " << real << imaginary << " i" << endl ; }

Cont.
void add_comp(Complex c1, Complex c2) ; void mul_comp(Complex c1, Complex c2) ; } ;
// End of the class definition

void Complex :: add_comp(Complex c1, Complex c2) { real = c1.real + c2.real ; imaginary = c1.imaginary + c2.imaginary ; } void Complex :: mul_comp(Complex c1, Complex c2) { real = (c1.real * c2.real)-(c1.imaginary * c2.imaginary) ; imaginary = (c1.imaginary * c2.real)+(c1.real * c2.imaginary) ;

Cont.
void main(void) { Complex com1(- 5.3, 3.2), com2, com3, com4 ; cout << "\n First complex number-->\n" ; com1.display_data( ) ; cout << "\n Second complex number-->\n" ; com2.enter_data( ) ; com2.display_data( ) ; com3.add_comp(com1, com2); cout << "\n Addition of two complex numbers-->\n" ; com3.display_data( ) ; com4.mul_comp(com1, com2) ; cout << "\n Multiplication of two complex numbers-->\n" ; com4.display_data( ) ; }

Output:
First complex number The complex number is: -5.3+3.2 i

Second complex number


Enter the real number: 7 Enter the imaginary number: 4.5 The complex number is: 7+4.5 i Addition of two complex numbers The complex number is: 1.7+7.7 i

Returning objects from the functions


#include<iostream.h> class Complex { private: float real, imaginary ; public: Complex( ) // Default Constructor { } Complex(float r, float i) // Constructor with two arguments { real = r ; imaginary = i ; } void enter_data(void) // Function to get the real and imaginary parts { cout << "\n Enter the real part of the complex number: " ; cin >> real ; cout << " Enter the imaginary part of the complex number: " ; cin >> imaginary ; }

Cont.
Complex add_comp(Complex c) /* Member function declarative with arguments and return value of type complex */ { Complex temp ; // temporary object temp.real = real + c.real ; //adds the real parts of // two complex numbers temp.imaginary = imaginary + c.imaginary ; // adds the imaginary // parts of two complex numbers return temp ; } void display_data(void) { if(imaginary >=0) cout << "\n\t The complex number is: " << real << "+" << imaginary << " i" << endl ; else cout << "\n\t The complex number is: " << real << imaginary << " i" << endl ; } }; // End of the class definition

Cont.
void main() { Complex c1, c2(4.5, -3.2), c3 ; c1.enter_data( ); cout << "\n First complex number***********" ; c1.display_data( ); cout << "\n Second complex number**********" ; c2.display_data( ); c3 = c1.add_comp(c2); cout << "\n The sum of the above two complex numbers********"; c3.display_data( ); } Output:
Enter the real part of the complex number: 2.5 Enter the imaginary part of the complex number: 3.8 First complex number*********** The complex number is: 2.5+3.8 i Second complex number********* The complex number is: 4.5-3.2 i The sum of above two complex numbers********** The complex number is: 7+0.6 i

Passing of objects by reference:


// This program illustrates the passing of the object arguments by reference. #include<iostream.h> class Complex { private: float real, imaginary ; public: Complex( ) { real = 0.0 ; imaginary = 0.0 ; } Complex(float r, float i) { real = r ; imaginary = i ; } void enter_data(void) { cout << "\n Enter the real number: " ; cin >> real ; cout << "\n Enter the imaginary number: " ; cin >> imaginary ; }

Cont.
void add_comp(Complex& c1, Complex& c2) /* Arguments are passed by reference */ { real = c1.real + c2.real ; imaginary = c1.imaginary + c2.imaginary ; } void display_data(void) { if (imaginary >= 0) cout << real << "+" << imaginary << "i" << endl ; else cout << real << imaginary << "i" << endl ; } }; // End of the class definition

Cont.
void main(void) { Complex com1(3.5, 5.6), com2 ; cout << "\n The first complex number is: " ; com1.display_data( ); com2.enter_data( ); cout << "\n The second complex number is: " ; com2.display_data( ); Complex com3 ; com3.add_comp(com1, com2); cout << "\n The sum of the two complex numbers is: " ; com3.display_data( ); } Output:
The first complex number is: 3.5+5.6i Enter the real number: 4.5 Enter the imaginary number: 7.5 The second complex number is: 4.5-7.5i The sum of two complex numbers is: 8-1.9i

Inline functions:

When the compiler sees a function call, it normally generates

a jump to the function. At the end of the function, it jumps back to the instruction following the call. While this sequence of events may save memory space, it takes some extra time.
void main() { display( ); . void display() {
if (imaginary >= 0)
cout << \n complex number is: << cout << real << + << imaginary << i ; else cout << \n complex number is: <<cout << real << imaginary << i ;

.....
display( ); .. .. display( ); .. ..

Fig: Repeated code placed in function

Cont.

To save the execution time in short functions, you may select to put the code in the function body directly in line with the code in the calling program.

In other words, each time there is a function call in the source file, the actual code from the function is inserted instead of a jump to the function.

When the program is compiled, the function body is actually inserted into the program whenever a function call occurs.

void main( )
{
if (imaginary >= 0) cout << \n complex number is: << cout << real << + << imaginary << i ; else cout << \n complex number is: <<cout << real << imaginary << i ; . . if (imaginary >= 0) cout << \n complex number is: << cout << real << + << imaginary << i ; else cout << \n complex number is: <<cout << real << imaginary << i ; . . if (imaginary >= 0) cout << \n complex number is: << cout << real << + << imaginary << i ; else

cout << \n complex number is: <<cout << real << imaginary << i ;
. .

Figure: Repeated code placed inline

Inline functions (cont.)

The compiler must have seen the function definition (not just the declaration) before it gets to the first function call. This is because it must insert the actual code into the program, not just the instruction to call the function. Sometimes the compiler will ignore the request and compile the function as a normal function. It might decide the function is too long to be inline.

Example:
inline void sum(int a, int b) // inline function definition { int c = a+b; cout << \n The sum of numbers is: << c ; } void main() { int x, y ; cout << \n Enter the values of x and y: ; cin >> x >> y; sum(x, y); }

Example:

// This program illustrates the use of the inline functions #include<iostream.h> class Rectangle { private: float length ; float breadth ; public: Rectangle( ) // Default constructor, without any argument { length =0; breadth = 0; } Rectangle(float l, float b) // Constructor with two arguments { length = l ; breadth = b ; } void Enter_lb(void) { cout << "\n\t Enter the length of the rectangle: " ; cin >> length ; cout << "\t Enter the breadth of the rectangle: " ; cin >> breadth ; } void Display_area(void) { cout << "\n\t The area of the rectangle = " << length*breadth ; } } ; // End of the class definition

Eg: Defining the inline functions outside the class


#include<iostream.h> class Rectangle { private: float length ; float breadth ; public: Rectangle( ) ; // Default constructor, without any argument Rectangle(float , float) ; // Constructor with two arguments void Enter_lb(void) ; void Display_area(void) ; } ; // End of the class definition

Cont.
Rectangle :: Rectangle( ) // Default constructor, without any argument { length =0; breadth = 0; } Rectangle :: Rectangle(float l, float b) // Constructor with two arguments { length = l ; breadth = b ; } inline void Rectangle :: Enter_lb(void) { cout << "\n\t Enter the length of the rectangle: " ; cin >> length ; cout << "\t Enter the breadth of the rectangle: " ; cin >> breadth ; } inline void Rectangle :: Display_area(void) { cout << "\n\t The area of the rectangle = " << (length*breadth) ; }

Static data member


The data members in a class can be defined as static. A static member variable is available only within the class, but it continues to live till the time program execution does not come to an end. If a data item in a class in defined as static , then only one such item is created for the entire class, no matter how many objects there are. A static data item is useful when all the objects of the same class must share a common item of information. Note that the type and scope of each static member variable must be defined outside the class definition. This is necessary because the static data members are stored separately rather than as a part of an object. They are also known as class variables, as they are associated with the class itself rather than with any class objects.

Static data member cont

The syntax for defining a static variable is: static data-type class_name :: variable_name ; By default, a static member variable is initialized to zero. However, some initial value can also be assigned to the variable. Static member variables are normally used to maintain the values common to the entire class. For example, there may be a situation when an object is required to know how many other objects of its class are in existence A static data member is not duplicated for each object; rather a single data item is shared by all objects
Pooja Jain 21

12 April 2014

Example
// This program illustrates the use of the static member variable in a class #include<iostream.h> class Objcount { private: static int count ; // Member Variable declared as static public: Objcount( ) // Constructor { count++ ; } void display(void) { cout << "\n cout = " << count ; } }; //*********Definition of the Static Member Variable count*************** int Objcount :: count ; // count is initialized to 0 by default
void main(void) { Objcount o1, o2, o3 ; o1.display( ) ; o2.display( ) ; o3.display( ) ; }

Output:
count = 3 count = 3 count = 3

Example2:

#include<iostream.h> class StaticSample { private: int count ; static int staticcount ; // static data public: StaticSample( ) // Default constructor, without any argument { count = 0; count++ ; staticcount++ ; } void display(void) { cout << "\n\tcount = " << count ; cout << "\n\tstaticcount = "<< staticcount << endl; } } ; // End of the class definition

Cont.
int StaticSample :: staticcount = 0 ; // Definition of static data
void main( ) { StaticSample s1 cout << \nAfter defining first object of StaticSample class---->\n; s1.display(); StaticSample s2 ; cout<<"\nAfter defining second objects of StaticSample class---->\n"; s1.display(); s2.display(); StaticSample s3; cout << "\n\n After defining third object of StaticSample class---->\n"; s1.display(); s2.display(); s3.display(); }

Cont.
Output:
After defining one object of StaticSample class----> count = 1 staticcount = 1 After defining two objects of StaticSample class----> count = 1 staticcount = 2 count = 1 staticcount = 2 After defining three objects of StaticSample class----> count = 1 staticcount = 3 count = 1 staticcount = 3 count = 1 staticcount = 3

staticcount=3

s1
count=1

s2
count =1

s3
count =1

Static data members/ functions


class Something { private: static int s_nValue; }; int Something::s_nValue = 1; // initializer int main() { // how do we access Something::s_nValue? }

12 April 2014

Pooja Jain

27

Static data members/ functions

While we could create a normal public member function to access s_nValue, wed then need to instantiate an object of the class type to use the function. We can do better. In this case, the answer to the problem is that we can also make member functions static.

12 April 2014

Pooja Jain

28

Static member function:

Like static member variables, the member functions can also be declared as static. A static member function can access only the other static member functions or static data, declared in the same class. A static member function is not part of the objects of a class. The static member functions can be called using the class name instead of its objects. The syntax for calling a static member function is: class_name :: function_name( ) ;

Static member functions

Like static member variables, static member functions are not attached to any particular object.

class Something { private: static int s_nValue; public: static int GetValue() { return s_nValue; } };
int Something::s_nValue = 1; // initializer

int main() { cout << Something::GetValue() << endl; }


12 April 2014 Pooja Jain 30

Example
// This program illustrates the use of the static member functions

#include<iostream.h> class Test { private: static int total ; // static data member public: Test( ) { total++ ; } static void display(void) // static member function { cout << "\n total = " << total << endl ; } }; // End of the class definition

Cont.
int Test :: total = 0 ; // Initialize total before main( ) void main(void) { cout << "\n When no object is created************** " ; Test :: display( ); // Accessing static member function Test obj1, obj2, obj3 ; cout << "\n When three objects have been created******" ; Test :: display( ); // Accessing static member function }
Output: When no object is created********************* total = 0 When three objects have been created****** total = 3

Static member functions cont

Static member functions have two interesting quirks worth noting. First, because static member functions are not attached to an object, they have no this pointer! This makes sense when you think about it the this pointer always points to the object that the member function is working on. Static member functions do not work on an object, so the this pointer is not needed. Second, static member functions can only access static member variables. They can not access non-static member variables. This is because non-static member variables must belong to a class object, and static member functions have no class object to work with!
Pooja Jain 33

12 April 2014

Friend function

A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class.

12 April 2014

Pooja Jain

34

Friend function

Friend function can access the private data. Friend function acts as an interface between two different classes. The syntax for declaration of the friend function is:
friend return_type function_name(argument(s) );

Some imp facts about friend functions

The keyword friend is placed only in the function declaration of the friend function and not in the function definition. It is possible to declare a function as friend in any number of classes. When a class is declared as a friend, the friend class has access to the private data of the class that made this a friend. A friend function, even though it is not a member function, would have the rights to access the private members of the class. It is possible to declare the friend function as either private or public. The function can be invoked without the use of an object. The friend function has its argument as objects.

12 April 2014

Pooja Jain

36

Example: Violating the concept of data hiding using friend function


class Sample { int value; public: Sample() { value = 5; } friend void funct(Sample); // Declaration of friend function };

void funct(Sample s) // Friend function Definition { cout << \n The value is: << s.value; } void main() { Sample samp; Output: funct(samp); The value is: 5 }

Example: Interface between two different classes


#include<iostream.h> class Two; // Forward declaration of class class One { int o ; public: One( ) { o = 5; } friend void sum(One, Two); //Friend function }; class Two { int t; public: Two( ) { t = 10; } friend void sum(One, Two); //Friend function };

Cont.
void sum(One one, Two two) // Friend function definition { int s = one.o + two.t ; cout << \n The sum = << s; } void main() { One o1; Two t2; sum(o1, t2); }
Output: The sum = 15

Defining the friend function inside the class


#include<iostream.h> class Two; // Forward declaration of class class One { int o ; public: One( ) { o = 5; } friend void sum(One, Two); //Friend function }; class Two { int t; public: Two( ) { t = 10; } friend void sum(One o, Two t); // Friend function definition { int s = one.o + two.t ; cout << \n The sum = << s; } };

Cont.
void main() { One o1; Two t2; sum(o1, t2); // Call to the friend function }

The const keyword

To prevent the normal variables from being modified. On function arguments to keep a function from modifying a variable passed to it by value or by reference. On member functions of a class. On member function arguments.

const member function

A constant member function guarantees that it will never modify any of its classs member data. To make a member function constant, the keyword const is placed after the declaration part, but before the function body. If the member function is declared inside the class but defined outside it, then it is necessary to use const in the declaration as well as definition.

Example

#include<iostream.h> #include<conio.h> class Sample { private: int data; public: Sample(int d = 0) { data = d; } void ChangeData( ) const // constant member function { data = data + 10; / * This is invalid */ } void DisplayData() { cout << \n data = << data; } }; void main() { Sample s(10) ; Compiler error: s.ChangeData() ; s.DisplayData() ; Cannot modify a const object }

Second version:
#include<iostream.h> #include<conio.h> class Sample { private: int data; public: Sample(int d = 0) { data = d; } void ChangeData( ) const ; // Declaration of constant member function void DisplayData() { cout << \n data = << data; } }; void Sample :: ChangeData( ) const // Definition of constant member function { data = data + 10; / * This is invalid */ } void main() { Sample s(10) ; s.ChangeData() ; s.DisplayData() ; }

Macros in C
#define CUBE(x) (x*x*x) #include<stdio.h> void main() { int a , c; printf(\n Enter any number:); scanf(%d, &a); c = CUBE(a); printf(\n The cube of a is %d, c ); }

Anda mungkin juga menyukai