Functions in C++ UNIT II

Embed Size (px)

Citation preview

  • 8/10/2019 Functions in C++ UNIT II

    1/29

    UNIT-II

  • 8/10/2019 Functions in C++ UNIT II

    2/29

    INTRODUCTION

    int main()

    {

    return 0;

    }

  • 8/10/2019 Functions in C++ UNIT II

    3/29

    contains the code for the function.The function definition for display_message () in program

    is given below the main () function. The general syntax of a function definition in C++ isshown below:

    Type name_of_the_function (argument list)

    {

    //body of the function

    }

    Here, the type specifies the type of the value to be returned by the function . It may be any valid C++

    data type. When no type is given, then the compiler returns an integer value from the function.

    the argument list is empty as you have already seen . The following function illustrates the concept of

    function definition .

  • 8/10/2019 Functions in C++ UNIT II

    4/29

    It is not always necessary for a function to have arguments or parameters. The functions add ( ) and

    divide ( ) did not contain any arguments. The following example illustrates the concept of passingarguments to function SUMFUN ( ):

  • 8/10/2019 Functions in C++ UNIT II

    5/29

  • 8/10/2019 Functions in C++ UNIT II

    6/29

    Parameter Passing Methods

  • 8/10/2019 Functions in C++ UNIT II

    7/29

  • 8/10/2019 Functions in C++ UNIT II

    8/29

    Static Data Members

    A data member of a class can be qualified as static. The properties of a static member

    variable are similar to that of a C static member variable has certain special characteristics.

    These are:-

    It is initialized to zero when the first object of its class is created. No other

    initialization is permitted.

    Only one copy of that member is created for the entire class and is shared by all the

    objects of that class.

    It is visible only within the class, built lifetime is the entire program.

    The class and scope of the static member variable is defined outside the class

    declaration. That is

    General form:

    return_type class_name :: static_variable;

    Program: illustrates the use of static data members.

    #include

    #include

    class number

    {

    private:

    static int c;

  • 8/10/2019 Functions in C++ UNIT II

    9/29

    int n;

    public:

    void normal( )

    {

    n=0;

    }

    void count( )

    {

    c ++;

    n++;

    cout

  • 8/10/2019 Functions in C++ UNIT II

    10/29

    value of n= 0 address of n= 3333 //for object B result

    value of c= 3 address of c= 1111

    value of n= 0 address of n= 4444 //for object C result

    Static Member Functions:

    Like static member variable, we can also have static member function.

    Characteristics of member functions

    A Static function can have access to only other static members declared in the

    same class.

    A static member function can be called using the class name.

    Class-name:: function-name;

    Lets have an example illustrating the above topics.

    #include

    class test

    {int code;

    static int count; // static member variable

    public:

    void setcode( )

    {

    code = ++count; // in this static data member is incrementing i.e count

    }

    void showcode( )

    {

    cout

  • 8/10/2019 Functions in C++ UNIT II

    11/29

    }

    }; //end of the class

    int test : : count; // definition of static data member

    int main ( )

    {

    test t1 , t2;

    t1.setcode ( );

    t2.setcode ( );

    test : : showcount ( );// accessing static function

    test t3;

    t3.setcode( );

    test : : showcount( );

    t1.showcode ( );

    t2.showcode ( );

    t3.showcode ( );

    return (0);

    } // end of int main

    Output:

    count : 2

    count : 3

    object number : 1

    object number : 2

    object number : 3

    Arrays of Objects

    We know that an array can be of any data type including struct. Similarly, we can

    also have arrays of variables that are of the type class.Such variables are called arrays of

    objects. Consider the following class

    class employee

    {

    char name[30];

    float age;

  • 8/10/2019 Functions in C++ UNIT II

    12/29

    public:

    void getdata();

    void putdata();

    };

    The identifier employee is a user-defined data type(class) and can be used to create objects

    that related to different categories of the employees.

    Example:

    employee manager[ 3 ]; // array of manager object

    employee foreman[ 10 ]; // array of foreman object

    employee worker[ 30 ]; // array of worker object

    The array manager contains three objects (managers), namely, manager[0],

    manager[1]and manager[2]of type employee class. Similarly for foremans and workers.

    We can access the members of class through arrays of object with dot operator.

    For example:

    manager [ i ] . getdata( );

    will display the data of the ithelement of array manager.

    Program:

    #include

    #include

    class Student

    {

    char name[ 30 ];

    int rno;

    float sgpa;

    public:

    void getdata( );

    void putdata( );

    };

    void Student : : getdata( )

    {

    coutname;

  • 8/10/2019 Functions in C++ UNIT II

    13/29

    coutrno;

    coutsgpa;

    }

    void Student : : putdata ( )

    {

    cout

  • 8/10/2019 Functions in C++ UNIT II

    14/29

    Only the address of the object is transferred to the function.

    The first method is called pass by value and the other is called pass by reference. When an

    address of the object that any changes made to the object directly on the actual object used in

    the call. This means pass by reference method is more efficient since it requires to pass only

    the address of object and not the entire object.

    Example:

    #inlude

    class Time

    {

    int hours;

    int minutes;

    public:

    void gettime (int h, int m)

    {

    hours = h;

    minutes = m;

    }

    void puttime ( )

    {

    cout

  • 8/10/2019 Functions in C++ UNIT II

    15/29

    t1.gettime(19, 45);

    t2.gettime(3,30);

    t3.sum( t1, t2 );

    cout

  • 8/10/2019 Functions in C++ UNIT II

    16/29

    c3.x = c1.x+c2.x; // x = real, y = ing

    c3.y = c1.y+c2.y;

    return ( c3 ); // returns objects c3

    }

    void complex : : show ( complex c)

    {

    cout

  • 8/10/2019 Functions in C++ UNIT II

    17/29

    Default arguments are signed only in functions prototype(declaration) and should not

    be repeated in the function definition.

    Whenever the function is called, if the function defines default arguments then it will

    goes to prototype and then jumps to function definition. Default values specified when the function is declared, and must be initialize the

    variables from right to left.

    We can not provide initialization of variables in the middle of the argument list.

    Some examples of function declaration with default values are:

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

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

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

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

    Program: Write a program to define function sum( ) with default arguments.

    # include

    int main( )

    {

    int sum( int a, int b=10, int c=15, int d=20); // function declration

    int a=2;

    int b=3;

    int c=4;

    int d=5;

    cout

  • 8/10/2019 Functions in C++ UNIT II

    18/29

    Sum=14

    Sum=29

    Sum=40

    Sum=47

    Sum=32

    Const Arguments

    The constant variable can be declared using const keyword. It makes variable value

    stable. The constant variable should be initialized while declaring.

    Syntax:

    a) const = value;

    b) ( const * );

    Example:

    int const x; //invalid

    int const x=5; //valid

    The const modifier assigns an initial value to a variable that cannot be changed later by

    program.

    In C++, an argument to a function can be declared as const as shown below.int function1( const char*p );

    int function2( const string &s);

    The 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 referenceor pointers.

    Inline Functions

    C++ proposes a new feature called inline function. It is a function that is expanded in

    line when it is invoked.

    That is, the compiler replaces the function call with the corresponding function

    code(something similar to macros expansion).

    It is easy to make a function inline, prefix the keyword inlineto the function

    definition. All inline functions must be defined before they are called.

    The inline functionsare defined as follows:

  • 8/10/2019 Functions in C++ UNIT II

    19/29

    inline function_header

    {

    function body

    }

    Some of the situations where inline expansion may not work are:

    If functions contains a loop, a switch, or a goto.

    For functions not returning values, if a return statement exists.

    If functions contain static variables.

    If functions are recursive

    Note: Inline expansion makes a program run faster because the overhead of a function

    call and return is eliminated.

    Program: illustrates the use of inline function.

    #include

    inline int mul( int x, int y)

    {

    return ( x * y);

    }

    inline float div(float p, float q)

    {

    return ( p / q);

    }

    int main( )

    {

    int a=4, b=2;

    float c=8.45,d=5.35;

    cout

  • 8/10/2019 Functions in C++ UNIT II

    20/29

    Making an outside function inline:

    We can make a outside defined member function as a inline function just using the

    qualifier inlinein header line of function definition.

    Example:

    class item

    {

    int number;

    float cost;

    public:

    void getdata (int a , float b); // declaration};

    inline void item :: getdata (int a, float b)

    {

    number = a,

    cost = b;

    }

    Function Overloading

    It is possible in C++ to use the same function name for multiple functions.

    Defining multiple functions with same name is known as function overloading or

    function polymorphism. Polymorphism means a function having many forms.

    The overloaded functions must be differing in no of arguments (or) types of

    arguments (or) order of argument list.

    Principles of function overloading:

    If two functions have the similar type in its number of arguments with data types, but

    the return types are different then those functions cannot be overloaded.

  • 8/10/2019 Functions in C++ UNIT II

    21/29

    Example:

    int sum( int , int );

    float sum( int , int );

    functions cannot be overloaded.

    The functions return type may be similar (or) void, but it must be different in number

    of arguments or arguments data types.

    Example1:

    sum( int , int );

    sum( float , float);

    In the above example number of arguments is same in both the functions, but data

    types are different. Hence the above functions can be overloaded.

    Example2:

    sum( int , int );

    sum( int , int ,int );

    In the above example data types of arguments are same in both the functions, but

    number of arguments is different. Hence the above functions can be overloaded.

    Program: illustrate the function overloading. (Without Class).

    #include

    #include

    int add( int x , int y) //two integer arguments

    {

    return x+y ;

    }

    float add( int x , float y) //one int and float arguments

    {

    return x+y;

    }

    float add( float x , int y) //one float and int arguments

    {

    return x+y;

    }

    float add( float x , float y) //two float arguments

    {

    return x+y;

  • 8/10/2019 Functions in C++ UNIT II

    22/29

    }

    int main( )

    {

    int a , b;

    float c , d;

    cout a >> b;

    cout c >> d;

    cout

  • 8/10/2019 Functions in C++ UNIT II

    23/29

    i = x*x;

    return i ;

    }

    float sqr( float y )

    {

    f = y*y;

    return f ;

    }

    }; //end of class

    int main( )

    {

    clrscr( );

    funover F ; // object created

    int a=5;

    float b=2.5;

    cout

  • 8/10/2019 Functions in C++ UNIT II

    24/29

    {

    member;

    public:

    members;

    friend void ( argument );

    };

    The function declaration should be preceded by the keyword friend.

    Function definition doesnt use either the keyword friend (or) scope resolution (::)

    operation

    A function can declared as friend in any no.of classes. Though it is non member

    function it has all access rights of private members of classes.

    Characteristics of Friend Functions:

    Not in the scope of class to which its declaredas friend.

    Since it is not in the scope of the class, it cant be called using the object of that class.

    It can be invoked like normal function without the help of any object.

    Cant access the members directly, it has to use an object name and dot operator .

    Can be declared either in public (or) private of class

    Have objects as arguments. Called by reference

    In this a pointer to the address of object is passed and the called function directly

    works on actual object used in the call

    The above method can be used to alter the values of private members of class

    Example-1: Program to illustrate Friend Functions:

    #include

    class A

    {

    int x;

    public:

    void accept( )

    {

    coutx;

  • 8/10/2019 Functions in C++ UNIT II

    25/29

    }

    friend int add_objects(A ,A ); //decleration of friend function

    };

    int add_objects(Aa1,Aa2) //definition of friend function

    {

    return (a1.x+a2.x);

    }

    void main

    {

    A a1, a2;

    A1.accept ();

    A2.accept ();

    cout

  • 8/10/2019 Functions in C++ UNIT II

    26/29

    void accept( )

    {

    couty;

    }

    friend int sumclasses(A , B);//friend function in two classes

    };

    int sumclasses(A a, B b) //friend function definition

    {

    return ( a.x + b.y );

    }

    int main( )

    {

    A a;

    B b;

    a.accept( );

    b.accept( );

    cout

  • 8/10/2019 Functions in C++ UNIT II

    27/29

    class A

    {

    int x;

    friend class B; // Be ready to friendship with B & it is for Class A

    public: void accept( )

    {

    coutx;

    }

    };

    class B

    {

    int y;

    public:

    void accept( )

    {

    cout >y;

    }

    void show(A a ) //It is getting data from class A

    {

    cout

  • 8/10/2019 Functions in C++ UNIT II

    28/29

    }

    Dynamic Memory Allocation and deallocation

    Whenever an array is defined, a specified amount of memory is set aside at compile

    time, which may not be utilized fully or may not be sufficient. If a situation arises in which

    the amount of memory required is unknown at compile time, the memory allocation can be

    performed during execution. Such a technique of allocating memory during runtime on

    demand is known as dynamic memory allocation.

    C++ provides the two special operators to perform memory management dynamically

    newoperator for dynamic memory allocation

    deleteoperator for dynamic memory deallocation

    These operators are simply the improved versions of the functions malloc(), calloc() and

    free() in C which are used for the same purpose.

    An object can be created by using new operator and destroyed by using delete as and

    when required. A data object created inside a block with new, will remain in existence unt il

    it is explicitly destroyed by using delete. Thus, the lifetime of an object is directly under our

    control.

    new operator:

    1) The new operator can be used to create objects of any type.

    The general format is:

    Pointer-varaible= new data-type;

    Here, the pointer-variable is a pointer of type data-type. The new operator allocates

    sufficient memory to hold a data object of type data-type (a valid data-type) and returns the

    address of the object. The pointer-variable holds the address of the memory space allocated.

    Example:

    int *p; //declaration of a pointer variable

    p=new int; //allocate two bytes of memory for p

  • 8/10/2019 Functions in C++ UNIT II

    29/29

    *p=25;

    2) We can also initialize memory using the new operator.

    The general format for initialization is:

    Pointer-variable =newdata-type(value);

    Example:

    int *p; //declaration of a pointer variable

    p=new int(25); //allocate two bytes of memory for p

    3) The new operator can also be used to create memory for any data type including user-

    defined data type such as arrays, structures and objects etc.

    The general format for creating dynamic memory for single dimensional array is

    Pointer-variable=new data-type [size];

    where the size is an integer variable.

    Example:

    int *arr;

    arr = new int[n]; //dynamically allocate memory for an array of size n

    arr[0]=10; //initialize the variables

    delete operator:

    When a data object is no longer required, it is destroyed to release the memory space

    for reuse.

    The general format is:

    delete pointer-variable;The pointer-variable is the pointer that points to a data object created with new.

    Example:

    delete p; //delete data object p of integer

    To release memory for an array the general format is

    delete [size] pointer variable; //where size is size of the array and it is optional

    Example

    delete [ ] arr ; // delete data object of an array