CPlus Pres 1

Embed Size (px)

Citation preview

  • 8/12/2019 CPlus Pres 1

    1/26

    1

    What is C++ ?

    C++ is a Object oriented programminglanguage. Initially named as C with

    classes.

    C++ was developed at AT & T BellLabs.

    C++ is superset of C.Three important facilities are added

    onto C.

    Classes

    Functions overloadingOperator overloading

    C++ also allows us to create hierarchyrelated objects.

    All C programs are also C++ programswith few differences.

  • 8/12/2019 CPlus Pres 1

    2/26

    2

    Input / Output

    # include OR# include

    using namespace std

    std: standard input/output

    iostream.h contains declaration forinput/output statements.

    (Naming conventions of header files may

    vary such as iostream.hpp

    cinand cout are predefined objectsin for single interface.

    cin >> number is an input statement& causes program to wait for user to

    type in a number.

    The identifier cin is a predefined object in C++ that corresponds to the standard

    input stream (keyboard).

  • 8/12/2019 CPlus Pres 1

    3/26

    3

    Operator >> is known as extraction orget from operator that extracts or getsvalue from keyboard.

    This corresponds to scanf( ) .The statement cout

  • 8/12/2019 CPlus Pres 1

    4/26

    4

    Cascading of I/O operators

    In the statement cin >> num1 >> num2the values are assigned from left to right

    cout

  • 8/12/2019 CPlus Pres 1

    5/26

    5

    Structure of C++ program

    Include files

    Class declaration

    Class functions definitions Main function program

  • 8/12/2019 CPlus Pres 1

    6/26

    6

    Data types of C++

    C++ Data Types

    User_ defined Built_in Derived type

    structure int array

    union char function

    class float pointer

    enumerated double

    void

  • 8/12/2019 CPlus Pres 1

    7/26

    7

    Void

    (Available in C & C++ both)

    Specifies the return type of a function thatdoes not return any value.

    Indicates empty argument list in a Function.Use of void in declaring generic pointers in

    C++.

    void *p ;

    int *i ;p = i ;

    // assigns ipointer to void pointer p

    i = p ; // not allowed

    So p can be assigned a pointer value ofany basic data types.

    void pointer may not be dereferenced.

  • 8/12/2019 CPlus Pres 1

    8/26

    8

    User Defined DT

    struct and unionare same as in C

    enumeratedDT slightly differ in C++enum shape {circle, square, triangle};

    0 1 2

    here shape becomes new typename and can be used to declare

    new variables.

    shape ellipse;

    enum color {red, blue=4, green=8}

    0

    enumcolor {red=5, blues=6, green=7}

    enum{off, on} {without name}

    0 1

    int switch1 = off;

    int switch2 = on;

  • 8/12/2019 CPlus Pres 1

    9/26

    9

    Pointers

    Available in C & C++

    int * i;i = & x;

    // address of x is assigned to i

    *i = 50;

    // 50 value assigned to a location// pointed out by i i.e. assigining

    // value 50 to x through indirection.

  • 8/12/2019 CPlus Pres 1

    10/26

    10

    Variable declaration

    In C, all variables are declared at thebeginning of the scope.

    But in C++, declaration of a variable beanywhere in the scope but before the first use.

    Advantage

    It makes program easier to understand.Disadvantage

    Cant see all variables at a glance used in thescope.

    Additional feature of C++ is in dynamicinitialization i.e., it permits runtime

    initialization.

    float average = sum / i;

  • 8/12/2019 CPlus Pres 1

    11/26

    11

    Constants

    C++ constants are to be initialized as:const int size =10;

    char name[size];

    enum { X, Y, Z};

    const X = 0; const Y = 1;

    const Z = 2;

    enum { X=10, Y=20, Z=15};

    const X = 10; const Y = 20;

    const Z = 15;

    Only integer constants can be definedusing enum data type.

  • 8/12/2019 CPlus Pres 1

    12/26

    12

    Reference variables

    C++ introduces a new kind of variablecalled reference variable that provides

    an aliasfor previously defined variable.

    data type &ref_var = var_name

    float total;

    float &sum = total;

    sum and total both are same locations.// a is initialized to new line constant

    char &a = \n

    Major application is in passingarguments to functions

    Call by reference mechanism isprovided in C++ explicitly

  • 8/12/2019 CPlus Pres 1

    13/26

    13

    Scope resolution operator

    { :

    int x = 10

    { int x =1;

    x is of inner block

    Scope resolution operator :: x = x +1;

    };

    } x is of outer block

    Declaration in an inner block hides adeclaration of the same variable in an outer

    block

  • 8/12/2019 CPlus Pres 1

    14/26

    14

    Memory management operators

    Along with malloc() & calloc(), C++also defines two unary operators new

    and delete. These operators operate on

    the free store of memory (also called

    free storeoperators).Life time of an object is directly under

    our control & unrelated to a block

    structure.

    Object created with new will remainuntil destroyed using delete.

    Including user defined

    pointer_var = new data_type;

    both of the same type

    int *p;float *q; int *p = newint[2];

    p = newint[2]; float *q = newfloat;

    q = newfloat;

  • 8/12/2019 CPlus Pres 1

    15/26

    15

    Creates memory space for an array of 2integers where p[0] refers to first element.

    delete p;

    delete q;

    delete p[ ] specify size

    In case of insufficient memory, newreturnsnull pointer.

    Advantages over malloc ( )

    Automatically computes the size ofdata object.

    Possible to initialize object whilecreating memory space. These can be overloaded.

  • 8/12/2019 CPlus Pres 1

    16/26

    16

    Functions in C++

    The function intmain ( )returns avalue of type int to the operatingsystem.

    (optional as it takes by default)

    If intbefore main ( ) is specifiedthen return statement for terminationbe used.

    Normal convention is that if value 0is returned then the program ransuccessfully while non zero value

    means some problem.

  • 8/12/2019 CPlus Pres 1

    17/26

    17

    Function prototyping is must in C++which gives compiler details as numberand type of arguments and return type.

    float volume (int, float, float);

    Should precede function definitionNo need to specify arguments.In C++, function without arguments canbe written as

    void display ( );

    Or

    void display (void);

    However in C, ( ) means any number ofarguments .In C++, this can be written openparameter list as voiddo-something ()

  • 8/12/2019 CPlus Pres 1

    18/26

    18

    Call by reference

    In C++, parameters can be passed as referenceor value but in C it is passed by value only.void swap (int &a, int &b)

    { int t =a; int t; t = a;

    a = b;

    b = t; In C++}

    Call - swap(m,n)

    void swap (int *a, int *b)

    { int t;t = *a;

    *a = *b; In C*b = t; }

    Call swap(&m,&n)

    Each argument in function must be declaredIndependently inside the parentheses.

  • 8/12/2019 CPlus Pres 1

    19/26

    19

    Return by reference

    A function can also return a referenceint &max (int &x, int &y);

    { if (x > y) return x;

    else return y;

    }

    Call max (a, b) returns a reference toeither a or bdepending upon whether value

    of a or b is returned.

    This implies that function call can appearon L.H.S in contrast to other programming

    Languages (including C).

    max ( a, b ) = -1

    assigns a = -1 if a > b

    b = -1, otherwise

  • 8/12/2019 CPlus Pres 1

    20/26

    20

    Default Arguments

    C++ allows to call a function withoutspecifying all its arguments.

    In such cases default values are specifiedwhen function is declared.

    Default values are always specified fromright to left.

    float amount (float p, int t = 3, float r = 0.15);

    Various Calls:

    value = amount (5000, 7, .12);

    value = amount (5000, 7)here value of r=0.15 is taken

    value = amount (5000)here t = 3 and r = 0 .15

  • 8/12/2019 CPlus Pres 1

    21/26

    21

    Function Overloading

    Same function name can be used to createvariety of tasks .

    It is called function polymorphismin OOP.// declarations

    int add (int, int);

    int add (int, int, int);

    double add (double, double);

    double add (int, double);double add (double, int);

    // Calls

    x = add(5,10);

    x = add(5,10,15);x = add(2.5,10.2);

    x = add(5,10.9);

    x = add(5.5,10);

  • 8/12/2019 CPlus Pres 1

    22/26

    22

    Compiler tries to find exact match wheretypes of actual arguments match.

    If exact match is not found then it performsinternal conversions.

    float long

    int float

    float int etc.

    For multiple matches error message isgenerated.

    long sq (long x);

    double sq (double x);

    sq (10)

    long double error message

    To avoid such situation sq( ) should be used.

  • 8/12/2019 CPlus Pres 1

    23/26

    23

    Inline function

    Ordinary function are compiled separatelyand are called as and when required.

    In order to save time/overheads in callingfunction & returning to called program, apowerful facility is available in C++ .

    Inline function is defined such asinline int sq (int x )

    {return (x *x) }

    call to inline

    function is same

    p = sq (2); q = sq (3);

    Inline function are not called at executiontime instead function call is expanded by

    the body of function.

  • 8/12/2019 CPlus Pres 1

    24/26

    24

    Inline modifier lets compiler mark aparticular function to be expended

    rather than compiled.

    C++ compiler may ignore your requestif your function is too long.

    Advantage of inline function is thatit can help you to write well designed,modular programs that remain efficient

    at the code level.

    const rate = 1.5

    inline float tax (x)

    {

    y = tax(p + 2); return (x * rate )

    };

    Speed benefits of inline functions will goif the size of function grows.

  • 8/12/2019 CPlus Pres 1

    25/26

    25

    In C, similar effect is achieved by macrodefinition defined by primitive # define.

    Here macro preprocessor performs textualsubstitution.

    # define rate 1.5

    # define tax (x) x * rates

    Macro call tax (p + 2) is expanded asp + 2 * rate which is not theintention.

    Macros cant have local variables and itdoes not even define a block. Macros also do not permit parameter

    checking.

    C++ solves the drawbacks of C macrowith inline function which is small

    function of one or two lines.

  • 8/12/2019 CPlus Pres 1

    26/26

    26

    Some situations where inline expansionmay not work.

    Functions returning values, ifa loop, a switchor a goto

    exist.

    Functions not returning valuesif a return statement exists.

    If functions contain staticvariables.

    If functions are recursive.