c++ an extension to c.ppt

Upload: scribdacct123

Post on 04-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 C++ an extension to C.ppt

    1/30

    C++, an extension to C

    Pooja Jain

    Senior Lecturer, JUITWaknaghat

  • 7/29/2019 C++ an extension to C.ppt

    2/30

    Preprocessor Directive The first line of the program

    # include

    tells the compiler to add the source file iostream.hto theprograms source file.

    It contains the declarations that are needed by the cout, cinidentifiers and the > operators.

    It might look like a program statement but is not a program

    statement.

    Instead it starts with a sign (#) called preprocess ordirective.

  • 7/29/2019 C++ an extension to C.ppt

    3/30

    Output using cout

    The identifiercout(pronounced asConsoleout) is actually an

    object. It is predefined in C++ to correspond to the standardoutput stream. (A stream is an abstraction that refers to a flowof data).

    The standard output stream normally flows to the screendisplay although it can be redirected to other output devices.

    The operator

  • 7/29/2019 C++ an extension to C.ppt

    4/30

    Input using cin The identifier cin (pronounced console in ) is an object,

    predefined in C++ to correspond to the standard input stream.

    This stream represents the data coming from the keyboard.

    The >> is the extraction or get from operator. It takes valuefrom the stream object on its left and places it in the variable

    on its right.

    Consider the following statements:

    int temp ;// declaration of int type variable

    cin >> temp ;// Input using cin object

    The second statement causes the program to wait for the userto type in an integer number. The resulting number is placed inthe variable temp.

  • 7/29/2019 C++ an extension to C.ppt

    5/30

    Example: Output/ Input using cout and cin objects#include

    void main()

    {

    int x;float f;

    charc;

    charstr[20] ;

    cout > x ;cout > f

    cout > c;

    cout > str ;

    cout

  • 7/29/2019 C++ an extension to C.ppt

    6/30

    Cascading of > operators

    When the operator () can be cascaded with cin in the same way, allowing

    the user to enter a series of values:

    Example:

    #include

    void main(){

    int x, float f, char c, char str[20];

    cout > x >> f >> c >> str ;// Cascading of input operator

    // Cascading of output operatorcout

  • 7/29/2019 C++ an extension to C.ppt

    7/30

    Flexibility in the declaration of the variables C requires that all variables be declared before the first

    executable statement. As against this, C++ allows

    definition of variables at the point where they are used. Thefollowing example illustrates this:

    #includevoid main(){

    int x , y ;cout > x ;cout > y;

    int z ;z = x + y;cout

  • 7/29/2019 C++ an extension to C.ppt

    8/30

    Function Prototypes:

    A function prototype is one of the major improvement added to C++function.

    The prototype describes the function interface to the compiler bygiving details such as: the number of arguments, the type ofarguments and the type of return value.

    The compiler uses the prototype to ensure that the types of actual

    arguments that you pass in a function call are the same as the typesof the formal arguments in the function definition.

    No C++ function can be called unless its prototype is available to thecompiler to crosscheck the argument type and the return value. Thisis known as strong type checking.

    Function prototype is a declaration statement in the calling programand is of the following form:

    return-type function_name (argument_list) ;

  • 7/29/2019 C++ an extension to C.ppt

    9/30

    Example:

    #include

    int sum(int, int); // Function prototype

    void main()

    {

    int a = 4, b = 6;

    int c = sum(a, b);// Calling functioncout

  • 7/29/2019 C++ an extension to C.ppt

    10/30

    Function overloading Overloading refers to the use of the same thing for different

    purposes. C++ also permits overloading of functions.

    Thus, one can use the same function name to createfunctions that perform a variety of different tasks. This isknown as the function overloading in OOP.

    Using the concept of the function overloading, one candesign a family of functions with one function name butwith different argument lists.

    The function would perform different operations dependingon the argument list in the function call.

    The correct function to be invoked is determined bychecking the number and the type of the arguments but not

    on the function type.

  • 7/29/2019 C++ an extension to C.ppt

    11/30

    Example: function overloading//Function Declarations#includeint sum( int , int );//prototype1

    int sum( int , int, int);//prototype2float sum( float, int);//prototype3intsum( char, char);//prototype4

    void main(){

    int i1=5, i2 =6;int i3 = sum(i1, i2); //Calling function1int i4 = sum(i1, i2, i3);// Calling function2float f1 = 4.5;float f2 = sum(f1, i1);// Calling function3charc1 =a, c2 = b;

    int c3 = sum(c1, c2);// Calling function4cout

  • 7/29/2019 C++ an extension to C.ppt

    12/30

    Cont.// Function Definitions

    int sum(int a, int b){

    return (a + b);}int sum(int a, int b, int c){

    return ( a + b + c ) ;}float sum(float f, int i){

    return ( f + i) ;

    }int sum(char c1, char c2){

    return (c1 + c2);}

    Sample Output:

    i3 = 11

    i4 = 22

    f2 = 9.5

    c3 = 195

  • 7/29/2019 C++ an extension to C.ppt

    13/30

    A reference, as the name suggests is like an alias.It is similar to the pointer. A reference is

    indicated by using the & operator in the same way

    you use the * operator to indicate a pointer.

    A pointer has to be de-referenced before you can accessa value using it, while a reference need not be. (see thethird statements of each segment)

    Segment2, using referenceint a = 5;

    int &p = a ;// p is a reference to variable acout

  • 7/29/2019 C++ an extension to C.ppt

    14/30

    A variable and its reference are so tightly inter-

    locked, that a change in one necessarily results

    in a change in the other.

    #include

    void main()

    {

    int i = 10;

    int &j = i ; // j is a reference to icout

  • 7/29/2019 C++ an extension to C.ppt

    15/30

    Cont.

    A reference must always be initialized. Like pointers, it isnot possible to first declare the reference in one statement,and then initialize it with the variable, in the next statement.

    //Using reference

    int a = 5 ;

    int &p ;// errorp = a ;

    //Using pointer

    int a = 5 ;

    int *p ;// validp = &a

  • 7/29/2019 C++ an extension to C.ppt

    16/30

    A variable can have multiple references. Changing the value

    of one of them effects a change in all others.

    #include

    void main(){

    int i = 5 ;

    int &j = i ;

    int &k =i ;int &l = i ;

    cout

  • 7/29/2019 C++ an extension to C.ppt

    17/30

    Cont.

    Once a reference variable has been defined to refer to aparticular variable, it cannot refer to any other variable.

    Though an array of pointers is acceptable, an array ofreferences is not.

  • 7/29/2019 C++ an extension to C.ppt

    18/30

    Referencing offers a clean, elegant an efficient way to pass

    parameters to functions that intend to change their values.

    #includevoid update1(int);

    void update2(int*);

    void update3(int&);

    void main(){

    int i =j = k = 5;

    update1(i) ; // Call by value

    update2(&j);// Call by pointer

    update3(k); // Call by referencecout

  • 7/29/2019 C++ an extension to C.ppt

    19/30

    Cont.

    void update1(int i);

    {

    i = i + 1;cout

  • 7/29/2019 C++ an extension to C.ppt

    20/30

    const qualifier

    If the keyword const, precedes the data type ofa variable, the value of the variable will notchange throughout the program.

    Any attempt to alter the value of the variabledefined with this qualifier will result into an errormessage from the compiler.

    The syntax is:constdata_type VAR_NAME = value ;

  • 7/29/2019 C++ an extension to C.ppt

    21/30

    Example:#include

    const float PI = 3.14 ;void main()

    {

    float radius ;

    cout > radius ;

    float area = PI*radius*radius ;

    cout

  • 7/29/2019 C++ an extension to C.ppt

    22/30

    newanddeleteoperators The dynamic memory allocation in C is done by using the

    functions: malloc() and calloc().

    The memory allocated from system heap using malloc() andcalloc() is vacated (deallocated) using the function free().

    C++ Offers a better way to accomplish the same job throughthe use of the newand deleteoperators.

    The new operator allocates memory from free store (in theC++ lexicon, heap is called free store).

    The deleteoperator returns the allocated memory back to the

    free store.

    The new operator, when used with the pointer to a data type,a structure, or an array, allocates memory for the item andassigns the address of that memory to the pointer. The delete

    operator does the reverse.

  • 7/29/2019 C++ an extension to C.ppt

    23/30

    Using new and delete operators

    The general form of using new operator is:

    data_type *variablename =new data_type ;

    Eg:int *p = newint ;

    float *q = new float ;

    *p = 25;// assigns 25 to the newly created int object*q = 7.5;// assign 7.5 to the float object.

    One can also initialize the memory using the new operator. This isdone as follows:

    pointer_variable =new data_type(value);// Here, value specifies// the initial value

    Eg:int *p = new int(25);

    float *q = new float(7.5);

  • 7/29/2019 C++ an extension to C.ppt

    24/30

    Cont.

    When a data object is no longer needed, it can be

    destroyed by the delete operator to release the memory

    space for the reuse. The general form of its use is:

    delete pointer-variable ;

    Eg:

    delete p ;

    delete q ;

  • 7/29/2019 C++ an extension to C.ppt

    25/30

    Allocating space for arrays, during run time The general form of one dimensional array is:

    data_type *poiter-variable =new data_type[size];

    To free a dynamically allocated array, use the following form of delete:

    delete [ ] pointer-variable ;Eg:

    int *p = newint[5]; //Creates a memory space for an array of 5 integers.

    When creating multi-dimensional arrays with new, all the array sizes mustbe supplied.

    Eg:array_ptr = newint[3][5][4] ; // legalarray_ptr = newint[m][5][4] ; // legalarray_ptr = newint[3]]5][ ] ; // illegalarray_ptr = new int[ ][5][4] ; // illegal

  • 7/29/2019 C++ an extension to C.ppt

    26/30

    Cont.

    To free a dynamically allocated array, we

    must use the following form of delete:

    delete [ ] pointer-variable ;

  • 7/29/2019 C++ an extension to C.ppt

    27/30

    Allocation and deallocation, [ usingmalloc() and free() functions in C ] and [new

    and delete operators in C++ ]

    Using C++struct List

    {int data ;List* next;

    };void main(){// Allocating space for one

    // object of List typeList* node = new List ;--------------delete node ;

    }

    Using Cstruct List

    {int data ;List* next ;

    } ;void main(){/* Allocating the space for one object of List type*/

    struct List * node = (List*) malloc(sizeof(List));--------------free(node);

    }

    int *p ;p = (int*)malloc(sizeof(int)*5);/* Allocating space------ for5 integer elements */------

    free(p);

    int *p ;p=new int[5];//Allocating space

    // for 5 integer elements------

    ------

    delete [ ] p ;

  • 7/29/2019 C++ an extension to C.ppt

    28/30

    Example:Allocating space for single-dimensional array of integers

    #include

    void main( )

    {

    int n ;cout > n ;

    int *p = new int [n];// Allocate the space for n integer elements

    cout

  • 7/29/2019 C++ an extension to C.ppt

    29/30

    Example: Allocating space for two-dimensional array of integers

    #include

    void main()

    {

    int row, col ;cout > row ;

    cout > col ;

    int **a = new int *[row];for(int i = 0; i < row; i++)

    {

    a[i] = new int[col];

    for(intj = 0; j < col ; j++)

    {cout

  • 7/29/2019 C++ an extension to C.ppt

    30/30

    Cont.cout