cpp latest me

Upload: mahaboob-basha

Post on 04-Apr-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Cpp Latest Me

    1/114

    1

    Procedure Oriented Programming

    In the POP approach, theproblem is viewed as a sequence of

    things to be done such as reading,

    calculating, and printing.

    A number of functions are

    written to accomplish these tasks. Theprimary focus is on Functions.

    1

  • 7/29/2019 Cpp Latest Me

    2/114

    2

    POP Approach Diagram

    Main Program

    Function-1 Function-2 Function-3

    Function-4 Function-5

    Function-6 Function-7 Function-8

    2

  • 7/29/2019 Cpp Latest Me

    3/114

    3

    In multi-function programming , many

    important data items are placed as globalso

    that they may be accessed by all thefunctions. Each function may have its own

    local data.

    Global data Global data

    Function-1

    Local data

    Function-2

    Local data

    Function-3

    Local data

    3

  • 7/29/2019 Cpp Latest Me

    4/114

    4

    Drawbacks in POP Approach

    Global data are move openly around the system

    from function to function.In a large program it is very difficult to identify

    what data is used by which function.

    In case we need to revise an external datastructure, we also need to revise all functionsthat access the data.

    Note: POP approach does not model real worldproblems very well, because functions areaction-oriented and do not really correspond tothe elements of the problem.

    4

  • 7/29/2019 Cpp Latest Me

    5/114

    5

    Object-Oriented Programming

    Object Oriented Programming treats

    data as a critical element in the program

    development and does not allow it to flowfreely around the system. It ties data more

    closely to the functions that operate on it,

    and protects it from accidental modificationfrom outside functions.

    5

  • 7/29/2019 Cpp Latest Me

    6/114

    6

    OOP allows decomposition of a

    problem into a number of entities called

    objects and then builds data and functions

    around these objects.

    The data of an object can be

    accessed only by the functions associated

    with that objects. The functions of oneobject can access the functions of other

    objects.6

  • 7/29/2019 Cpp Latest Me

    7/114

    7

    OOPs Approach Diagram

    Data

    Functions

    Data

    Functions

    Object A Object B

    Functions

    Data

    Object C

    Communication

    7

  • 7/29/2019 Cpp Latest Me

    8/114

    8

    OOPs principle

    Encapsulation and Data Hiding:

    The wrapping up of data and functions into a

    single unit (called class) is known as

    encapsulation.The data is not accessible to the outside world,

    and only those functions which are wrapped

    in the class can access it. These functionsprovide the interface between the objects

    data and the program.8

  • 7/29/2019 Cpp Latest Me

    9/114

    Key concepts of OOP

    1.Object:

    Objects are primary run-time entities in an

    object oriented programming. An object is

    a specimen of a class. Objects occupyspace in memory. Every object has its own

    properties or features. The action of the

    object depends upon the member functiondefined within its class.

    9

  • 7/29/2019 Cpp Latest Me

    10/114

    Commonly available objects

    10

  • 7/29/2019 Cpp Latest Me

    11/114

    2.Classes:

    A class is grouping of objects having identical

    properties, common behavior, and sharedrelationship. The entire group of data and code

    of an object can be built as a user-defined data

    type using class. Objects are nothing butvariables of type class. Once a class has been

    declared, the programmer can create a number

    of objects associated with that class.

    11

  • 7/29/2019 Cpp Latest Me

    12/114

    v

    Class : Bus

    Properties: company, model,

    color, capacity

    Actions: speed(), average()

    Class : computerProperties: brand, price,

    hard disk, RAM sizeActions: processing speed(),display()

    12

  • 7/29/2019 Cpp Latest Me

    13/114

    3.Method:

    An operation required for an object when coded

    in a class is called method. The operations areto be defined in a class. All objects in a class

    perform certain common actions or operations.

    A class contains private data members and

    public methods or member functions. Generally

    the data members are declared private andmember functions are declared public.

    13

  • 7/29/2019 Cpp Latest Me

    14/114

    4. Data Abstraction

    Abstraction directs to the procedure of

    representing essential features without

    including the background details. Class uses the

    theory of abstraction and is defined as a list of

    abstract properties such as size, cost, height and

    a few functions to operate on these properties.

    14

  • 7/29/2019 Cpp Latest Me

    15/114

    5. Encapsulation:

    The packing of data and functions into a singlecomponent is called encapsulation. Data hiding

    can be accomplished with encapsulation. In c++,

    the data is not accessible by outside functions.Only those functions that are able to access the

    data are defined within the class.

    15

  • 7/29/2019 Cpp Latest Me

    16/114

    6.Inheritance:

    Inheritance is the method by which objects of

    one class get the properties of objects ofanother. In object oriented programming,

    inheritance provides the thought of reusability.

    The programmer can add new properties to theexisting class without changing it.

    16

  • 7/29/2019 Cpp Latest Me

    17/114

    7.Polymorphism:

    Polymorphism allows the same function to

    act differently in different classes.

    Line

    Display()

    Dotted objects

    Display()

    stars

    Display()

    Asterisk

    Display()

    17

  • 7/29/2019 Cpp Latest Me

    18/114

    Streams in C++:

    C++ provides a new way to perform the input and

    output operations called iostream method.The standard header file iostream.h contains a set of

    small and specific general purpose functions for

    handling input and output data.

    The standard input and output operations in C++ are

    normally performed by using the I/O stream as cin for

    input and cout for output.

    18

  • 7/29/2019 Cpp Latest Me

    19/114

    cout:

    Syntax:

    coutvarn;

    19

  • 7/29/2019 Cpp Latest Me

    20/114

    Frequently used unformatted input andoutput functions:

    cin

    get()

    getline()

    read()

    cout

    put()

    write()

    20

  • 7/29/2019 Cpp Latest Me

    21/114

    get() and put() functions:

    The single character input and output

    operations in c++ can be done with the help ofthese functions.

    The get() is used to read a character and theput() is used to display the character on the

    screen.

    The syntax is:

    cin.get(ch) cout.put(ch)21

    l () d() d ()

  • 7/29/2019 Cpp Latest Me

    22/114

    getline(), read() and write():

    The getline() and write() functions are useful in

    string input and output. The getline() reads thestring including white spaces.

    The object cin calls the function as:cin.getline(variable, size);

    22

    d()

  • 7/29/2019 Cpp Latest Me

    23/114

    read():

    It also reads the text through the keyboard.

    Syn: cin.read(variable,size);

    When we use read statement it is necessary to

    enter character equal to the number of size ofspecified. The getline() statement terminates

    the accepting data when enter is pressed where

    as the read() continues to read characters tillthe no. of characters entered are equal to the

    size specified.23

  • 7/29/2019 Cpp Latest Me

    24/114

    write():

    The write() function is used to display the string on

    the screen. Its format is the same as getline() but thefunction is exactly opposite.

    Syn: cout.write(variable, size);

    The cout.write() statement displays only specified

    number of characters given in the second argument,

    though actual string may be more in length.

    24

    M i l f i

  • 7/29/2019 Cpp Latest Me

    25/114

    Manipulator functions:

    These are special stream functions that change

    certain characteristics of the input and output.

    The main advantage of these is that they

    facilitate the formatting of input and outputstreams.

    To carry out the operations of these in a user

    program, the header file input and outputmanipulator must be included.

    25

    P d fi d i l t

  • 7/29/2019 Cpp Latest Me

    26/114

    Predefined manipulators:

    endl

    hex, dec, oct

    setbase

    setw

    setfill

    setprecision

    ws26

    1 Th dl i t t i l t t

  • 7/29/2019 Cpp Latest Me

    27/114

    1.The endl is an output manipulator togenerate a carriage return.

    2. The setbase() manipulator is used to

    convert the base of one numeric valueinto another base. Following are thecommon base converters.

    dec (base 10) hex (base 16)oct (base 8)

    27

    3 Th t () t d f th t idth It

  • 7/29/2019 Cpp Latest Me

    28/114

    3. The setw() stands for the set width. Itis used to specify the minimum no. of

    character positions on the output fielda variable will consume.

    4. The setfill() manipulator function is

    used to specify a different character tofill the unused field width of the value.

    5. The setprecision() is used to controlthe number of digits of an ouputstream display of a floating point value.

    28

  • 7/29/2019 Cpp Latest Me

    29/114

  • 7/29/2019 Cpp Latest Me

    30/114

    showpoint:

    The showpoint flat is used to show the decimal

    point for all floating point values. By default, thenumber of decimal position is six.

    Syntax: cout.setf(ios::showpoint);

    Precision:

    The precision member function is used to display

    the floating point value as defined by the user.

    Syntax: cout.precision(int n);

    30

  • 7/29/2019 Cpp Latest Me

    31/114

  • 7/29/2019 Cpp Latest Me

    32/114

    fixed:

    When fixed is set, the value is inserted using

    decimal notation with the specified number ofprecision digits following the decimal point.

    Syntax: cout.setf(ios::fixed, ios::floatfield);

    32

  • 7/29/2019 Cpp Latest Me

    33/114

    Left:

    If left is set, the inserted data will be flush left in

    a field of characters width wide. The extra space,if any, will be filled by the fill character.

    Syntax: cout.setf(ios::left, ios::adjustfield);

    Right:

    Cout.setf(ios::right, ios::adjustfield);

    33

    Some important keywords in c++:

  • 7/29/2019 Cpp Latest Me

    34/114

    Some important keywords in c++:

    catch class delete

    friend inline new

    operator private protected

    public template this

    throw try virtual

    34

    Dynamic initialization:

  • 7/29/2019 Cpp Latest Me

    35/114

    Dynamic initialization:

    The declaration and initialization of variable in a

    single statement at any place in the program iscalled dynamic initialization.

    In C, initialization of variables can be done at any

    place but the variable must be declared at thebeginning of the program.

    35

  • 7/29/2019 Cpp Latest Me

    36/114

    Operators in C++:

    Operator Description

    > extraction operator

    :: scope access (or resolution)operator

    delete memory release operatornew memory allocation operator

    & referencing operator36

    Referencing operator(&):

  • 7/29/2019 Cpp Latest Me

    37/114

    Referencing operator(&):

    The referencing operator is used to define

    referencing variable. A reference variable analternative name for previously defined variable.

    Syn: data_type ref_var_name = var_name

    Ex: int a = 10;

    int &b = a;

    If we modify the value of a, it results in change inreference variable too.

    Note: Array of references is not allowed.37

    Scope access operator:

  • 7/29/2019 Cpp Latest Me

    38/114

    Scope access operator:

    The scope access operator (::) allows a

    programmer to access a global name evenif it is hidden by a local re-declaration ofthat name.

    38

    Memory management operators:

  • 7/29/2019 Cpp Latest Me

    39/114

    Memory management operators:

    In C, we have had the functions malloc(),

    calloc() and realloc() to allocate memorydynamically at runtime in the program. Thefree() function is used to release the

    resources allocated by these functions. C++also allows us to use these.

    In addition, C++ provides us with two newoperators new and delete. The newoperator creates an object and delete

    destroys it.39

    The advantages of new operator over

  • 7/29/2019 Cpp Latest Me

    40/114

    The advantages of new operator overmalloc():

    1.The new operator itself calculates the size ofthe object with the use of sizeof operator.

    2.It returns the pointer type. The programmers

    need not take care of type casting.

    3.The new operator allocates memory andinitializes the object at once.

    4.The new and delete operators are very easy insyntax. They can be overloaded.

    40

  • 7/29/2019 Cpp Latest Me

    41/114

    The delete operator:

  • 7/29/2019 Cpp Latest Me

    42/114

    The delete operator:

    Syntax:

    delete

    delete[element size]

    Ex:

    delete p;

    delete[5]p or delete[]p;

    42

    Functions with Default arguments:

  • 7/29/2019 Cpp Latest Me

    43/114

    Functions with Default arguments:

    43

    C++ allows us to call a function without specifying all

    its arguments. In such cases, the function assigns adefault value to the parameter which doesnt have a

    matching argument in the function call. Default values

    are specified when the function is declared. Thecompiler looks at the prototype to see how many

    arguments a function uses and alerts the program for

    possible default values.

    Declaration of a class:

  • 7/29/2019 Cpp Latest Me

    44/114

    Declaration of a class:

    A class definition is a process consisting the

    following steps:1.Definition of a class.

    2.The internal representation of data structuresand storage.

    3.The internal implementation of the interface.

    4.The external operations for accessing andmanipulating the instance (object) of the class.

    44

    Class and Objects

  • 7/29/2019 Cpp Latest Me

    45/114

    Class and Objects

    A class is used to pack data and functions

    together. The class has a mechanism toprevent direct access to its members,which is the central idea of oop.

    Syntax:

    {

    private:

    public:

    };45

  • 7/29/2019 Cpp Latest Me

    46/114

    Declaration of objects:

    A class declaration builds the structure ofobject. The member variables and functions

    are combined in the class. The declarationof object is same as declaration of variablesdata types. Defining objects of class type is

    known asclass

    instantiation

    .

    46

    An object is an abstract unit having following

  • 7/29/2019 Cpp Latest Me

    47/114

    An object is an abstract unit having followingproperties:

    1.It is an individual.2.It points to a thing, either physical or logical

    that is identifiable by the user.

    3.It holds data as well as operation method thathandles data.

    4.Its scope is limited to the block in which it isdefined.

    47

    Private member function:

  • 7/29/2019 Cpp Latest Me

    48/114

    Private member function:

    To execute private member function, it must

    be invoked by public member function ofthe same class. A member function of aclass can invoke any other member function

    of its own class. This method of invokingfunction is known as nesting of memberfunctions.

    48

  • 7/29/2019 Cpp Latest Me

    49/114

  • 7/29/2019 Cpp Latest Me

    50/114

  • 7/29/2019 Cpp Latest Me

    51/114

  • 7/29/2019 Cpp Latest Me

    52/114

    Ouside member function inline:

  • 7/29/2019 Cpp Latest Me

    53/114

    An inline member function is similar to macros.

    Call to inline function in the program, puts thefunction code in the caller program. This is knows as

    inline expansion. Inline functions are also called open

    subroutines because their code is replaced at the

    place of function call in the caller function. The

    normal functions are called closed subroutines

    because when such functions are called, the control

    passes to the function.

    By default all member functions defined inside

    the class are inline functions.53

  • 7/29/2019 Cpp Latest Me

    54/114

    Memory allocation for object :

  • 7/29/2019 Cpp Latest Me

    55/114

    e o y a ocat o o object

    Common for all objects

    Member function 1 Member function 2

    Member variable1

    Member variable2

    Member variable1

    Member variable2

    Memory created when

    functions defined

    Memory created when

    Object 2bject 1

    55

    The memory space for objects is allocated only

  • 7/29/2019 Cpp Latest Me

    56/114

    y p j y

    when they are declared and not when the class is

    specified. Actually, the member functions are

    created and placed in the memory space only

    when they are defined as a part of a class

    specification. Since all the objects belonging to

    that class use the same member functions, noseparate space is allocated for member functions.

    Only space for member variables is allocated

    separately for each object. This is essentialbecause the member variables will hold different

    data values for different objects.56

    Static Data Members

  • 7/29/2019 Cpp Latest Me

    57/114

    When we declare a member variable static, we are

    telling the compiler that only one copy of that

    variable will exist and that all objects of the class

    will share that variable. Unlike regular data

    members, individual copies of a static member

    variable are not made for each object. No matterhow many objects of a class are created, only one

    copyof a static data member exists. Thus, all

    objects of that class use that same variable. Allstatic variables are initialized to zero before the

    first object is created.57

  • 7/29/2019 Cpp Latest Me

    58/114

  • 7/29/2019 Cpp Latest Me

    59/114

  • 7/29/2019 Cpp Latest Me

    60/114

  • 7/29/2019 Cpp Latest Me

    61/114

    Friend Functions

  • 7/29/2019 Cpp Latest Me

    62/114

    62

    The private members cannot be accessed from

    outside the class. That is, a non-memberfunction cannot have an access to the private

    data of a class.

    When a private data member is changed topublic category, it violates the whole concept of

    data hiding and data encapsulation. To solve

    this problem, a friend function can be declaredto have access to these data members.

    Friend is a special mechanism for letting non-

  • 7/29/2019 Cpp Latest Me

    63/114

    63

    p g

    member functions access private data. A friend

    function may be either declared or defined

    within the scope of a class definition. The

    keyword friend inform the compiler that it is not

    a member function of the class.

    Syntax:

    Friend return_type fun_name(parameters);

    Granting friendship to another class:

  • 7/29/2019 Cpp Latest Me

    64/114

    64

    g p

    A class can have friendship with another class.

    For example, let there be two classes, first and

    second. If the class first grants friendship with

    the other class second, then the private data

    members of the class first are permitted to be

    accessed by the public member functions of the

    class second. But on the other hand, the public

    member functions of the class first cannotaccess the private members of the class second.

  • 7/29/2019 Cpp Latest Me

    65/114

    Two classes having the same friend:

  • 7/29/2019 Cpp Latest Me

    66/114

    66

    g

    A non-member function may have friendship

    with one or more classes. When a function has

    declared to have friendship with more than

    one class, the friend classes should have

    forward declaration. It implies that it needs to

    access the private members of both classes.

    A friend function can be called by

  • 7/29/2019 Cpp Latest Me

    67/114

    67

    A friend function can be called by

    reference. In this case, local copies of the

    objects are not made. Instead, a pointer tothe address of the object is passed and the

    called function directly works on the actual

    object used in the call.

    Constructors and destructors

  • 7/29/2019 Cpp Latest Me

    68/114

    68

    A constructor is a special member function

    whose task is to initialize the objects of its

    class. The constructor is invoked whenever an

    object of its associated class is created. Its

    name is same as the class name.

    A destructor is used to destroy the objects that

    have been created by a constructor. Its name

    is the same as class name but preceded by a

    tilde(~) operator.

  • 7/29/2019 Cpp Latest Me

    69/114

    Constructors with arguments:

  • 7/29/2019 Cpp Latest Me

    70/114

    70

    The constructors with arguments are called

    parameterized constructors. For these

    constructors, it is necessary to pass values to

    the constructor when object is created.

    Function overloading:

  • 7/29/2019 Cpp Latest Me

    71/114

    71

    g

    In C++, it is possible to use the same function

    for a number of times for different intentions.

    Defining multiple functions with same name is

    called function overloading or function

    polymorphism.The overloaded function must be different in its

    argument list and with different data types.

    Principles of function overloading:

  • 7/29/2019 Cpp Latest Me

    72/114

    72

    p g

    1. If two functions have the similar type and number

    of arguments (data type), the function cannot be

    overloaded.

    sum(int, int, int);

    sum(int, int);

    sum(int, int, int);

    sum(float, float, float);

    These two can be overloaded.

    2. The compiler attempts to find an accurate

  • 7/29/2019 Cpp Latest Me

    73/114

    73

    p p

    function definition that matches in types and

    number of arguments and invokes that function.

    The arguments passed are checked with all

    declared functions. If matching function is found

    then that function gets executed.

    3. If there is no accurate match found, compiler

    makes the implicit conversion of actual argument.

    For example, char is converted to int and float is

    converted to double.

  • 7/29/2019 Cpp Latest Me

    74/114

  • 7/29/2019 Cpp Latest Me

    75/114

    Destructors:

    f

  • 7/29/2019 Cpp Latest Me

    76/114

    76

    Destructor is a special member function like

    constructor. Destructors destroy the class objects

    created by constructors. The destructors have thesame name as their class, preceded by tilde (~).

    For local and non-static objects, the destructor is

    executed when the object goes out of the scope. Incase the program is terminated by using return

    statements, the destructor is executed for every

    object existing at that time. It is not possible to

    define more than one destructor. The destructor is

    only one way to destroy the object.

    Operator overloading:

    h h b l d f d d l k

  • 7/29/2019 Cpp Latest Me

    77/114

    77

    C++ has the ability to treat user-defined data type like

    the one they were built-in type. User-defined data

    types created from class or struct are nothing butcombination of one or more variables of basic data

    types. The compiler knows how to perform various

    operations using operators for built-in types. Thecompiler would throw an error if we want to perform

    an operation between two objects using operators.

    Therefore, for the objects, the operation routine

    must be defined by the programmer.

    The key word operator defines a new action or

  • 7/29/2019 Cpp Latest Me

    78/114

    78

    operation to the operator.

    Syntax:

    Return_type operatorop_symbol(parameters)

    {

    statement 1;

    statement 2;}

    The keyword operator, followed by an operator

    symbol, defines a new (overloaded) action of thegiven operator.

    Rules for overloading operators:

  • 7/29/2019 Cpp Latest Me

    79/114

    79

    1. Overloading of an operator cannot change the

    basic idea of an operator. When an operator is

    overloaded, its properties like syntax, precedence

    and associatively remain constant.

    Ex: a+ = b; is a=a+b;

    2. Overloading of an operator must never change itsnatural meaning. An overloaded operator + can be

    used for subtraction of two objects, but this type

    of code decreases the utility of the program.

    When ++ and operators are overloaded, the system

    d i h h h

  • 7/29/2019 Cpp Latest Me

    80/114

    80

    cant determine whether the operators are

    overloaded for prefix or postfix operations. Hence,

    the operator must be overloaded in such a way that itwill for both prefix and postfix operations. To make a

    distinction between prefix and postfix notation, a new

    syntax is used to indicate postfix operator overloadingfunction. The syntaxes are:

    operator ++ (int) //postfix notation

    operator ++() //prefix notation

  • 7/29/2019 Cpp Latest Me

    81/114

    Class inheritance uses this general form:

  • 7/29/2019 Cpp Latest Me

    82/114

    82

    Class inheritance uses this general form:

    class derived-class-name: access base-class-name

    { // body of class

    };

    The access status of the base-class members inside

    the derived class is determined by access.

    Private inheritance:

  • 7/29/2019 Cpp Latest Me

    83/114

    83

    When a base class is privately inherited by a derived

    class, public and protected members of the base

    class become the private members of the derived

    class. Therefore the public members of the base class

    can only be accessed by the member functions of thederived class.

    Public inheritance:

  • 7/29/2019 Cpp Latest Me

    84/114

    84

    When a base class is publicly inherited by a derived

    class, public members of the base class become thepublic members of the derived class and protected

    members of the base class become the protected

    members of the derived class. Therefore publicmembers of the base class can accessible to the

    objects of the derived class.

    Protected inheritance:

  • 7/29/2019 Cpp Latest Me

    85/114

    85

    When the base class is protectedly inherited by a

    derived class, public and protected members of thebase class become the protected members of the

    derived class. Therefore public members of the

    base class can be accessed by the member functionsof the derived class.

    Inheritance and protected Members:

    A pri ate member of a base class is not

  • 7/29/2019 Cpp Latest Me

    86/114

    86

    A private member of a base class is not

    accessible by other parts of our program, including

    any derived class. However, protected membersbehave differently. If the base class is inherited as

    public, then the base class' protected members

    become protected members of the derived class andare, therefore, accessible by the derived class. By

    using protected, you can create class members that

    are private to their class but that can still be inherited

    and accessed by a derived class.

  • 7/29/2019 Cpp Latest Me

    87/114

    Types of inheritance:

  • 7/29/2019 Cpp Latest Me

    88/114

    88

    1. Single inheritance: If a class inherits from one base

    class is called single inheritance.2. Multiple inheritance: If a class inherits from more

    than one base class is called multiple inheritance.

    3. Multilevel inheritance: If a class derived from aderived class is class multilevel inheritance.

    4. Hierarchical inheritance: The mechanism of

    deriving more than one derived class is called

    hierarchical inheritance.

  • 7/29/2019 Cpp Latest Me

    89/114

    89

    Constructorsin

    inheritance

    Case-1:When base class has default constructor(without

  • 7/29/2019 Cpp Latest Me

    90/114

    90

    When base class has default constructor(withoutarguments), the derived class need not have a

    constructor function.case-2:However, if any base class contains a constructor

    with one or more arguments, then it ismandatory for the derived class to have aconstructor with arguments and pass thearguments to the base class constructors.

    while applying inheritance we usually createobjects using the derived class Thus it makes sense

  • 7/29/2019 Cpp Latest Me

    91/114

    91

    objects using the derived class. Thus, it makes sense

    for the derived class to pass arguments to the base

    class constructor.The constructor of the derived class receives the

    entire list of values as its arguments and passes

    them on to the base class constructors in the order inwhich they are declared in the base class.

    When both the derived and base classes contain

    constructors, the base class constructor is executed

    first and then the derived class

    constructor is executed next.

    C++ supports a special constructor member functionsuch a situations

  • 7/29/2019 Cpp Latest Me

    92/114

    92

    such a situations.

    Syntax:

    Derived-constructor(args list) :base-constructor(arg1),

    base-constructor(arg2),...

    {// body of the derived

    // class constructor

    . . .

    . . .

    }

    Templates:

    Template is a concept which enables us to define

  • 7/29/2019 Cpp Latest Me

    93/114

    93

    Template is a concept which enables us to define

    generic classes and functions and thus provides

    support for generic programming.Generic programming:

    It is an approach where generic types are used as

    parameters in algorithms so that they for a variety ofsuitable data types and data structures.

    A template can be used to create a family of classes orfunctions

  • 7/29/2019 Cpp Latest Me

    94/114

    94

    functions.

    For example, a class template for an array class would

    enable us to create arrays of various data types.Similarly, we can define a template for a function, say

    sum(), that would help us create various versions of

    sum() for adding int, float and double data types.A template can be considered as a kind of macro.

    When an object of a specified type is defined for

    actual use, the template definition for that class is

    substituted with the required data type. Template can

    be called parameterized classes or functions.

  • 7/29/2019 Cpp Latest Me

    95/114

    95

    Definition of class template:

    Template class

    Class class_name

    {

    //data members and functions

    }

    Normal function template:

    l i

  • 7/29/2019 Cpp Latest Me

    96/114

    96

    Declaration:

    template class

    function_name()

    {//code

    }

    Template with multiple parameters:

  • 7/29/2019 Cpp Latest Me

    97/114

    97

    Template with multiple parameters:

    TemplateClass class_name{

    class dec & def}

    Function templates with more arguments:

  • 7/29/2019 Cpp Latest Me

    98/114

    98

    Function templates with more arguments:

    Templateret_type fun_name(parameters of template type)

    {

    statement 1;

    statement 2;

    statement 3;

    }

    Exception handling

  • 7/29/2019 Cpp Latest Me

    99/114

    99

    Errors

    logical errors syntactic errors

    Logical errors occur due to poor understanding of the

    problem and solution procedure.Syntactic errors occur due to poor understanding of the

    language itself.

    Other than these two, we come across peculiar problems

    which are called exceptions. These are runtime anomalieslike division by zero, access to an array outside of its bounds,

    running out of disk space etc.,

  • 7/29/2019 Cpp Latest Me

    100/114

    100

    Exception handling allows us to manage run-time errors in an orderly fashion. Using exception

    handling, our program can automatically invoke an

    error-handling routine when an error occurs.

    C++ exception handling is built upon three keywords: try,catch, and throw. In the most general terms, program

  • 7/29/2019 Cpp Latest Me

    101/114

    101

    , g , p g

    statements that we want to monitor for exceptions are

    contained in a try block. If an exception (i.e., an error) occurs

    within the try block, it is thrown (using throw). The exception

    is caught, using catch, and processed.

    try

    blockDetects and throwsan exception

    catchblockDetects and throws

    an exception

    Exception

    object

    try

    The general form of try, throw and catch:

  • 7/29/2019 Cpp Latest Me

    102/114

    102

    try

    {

    ...throwexception

    .

    }

    catch (type arg)

    {

    // catch block

    }

    When the tryblock throws

    an exception, the programcontrol leaves the try block

    and enters the catch

    statement of the catch

    block. Exceptions are

    objects used to transmit

    information about a

    problem.

    throw

    Function invoked by try block throwing exception

  • 7/29/2019 Cpp Latest Me

    103/114

    103

    try

    blockInvokes a function thatcontains exception

    catchblockCatches and handles

    the exception

    Throw

    Exception

    throw

    pointFunction that causes

    an exception Invoke

    function

  • 7/29/2019 Cpp Latest Me

    104/114

    As soon as the an exception is thrown, the

  • 7/29/2019 Cpp Latest Me

    105/114

    105

    compiler searches for appropriate match by matching

    catch() block. The matching catch() block is executed

    and control passes to the successive statement after

    the last catch() block. In case no match is found, the

    program terminates.

    In multiple catch() statement, if objects of manycatch statements are similar to type of an exception,

    in such a situation the first catch () block that matches

    is executed.

    Catching all Exceptions:In some situations, we may not be able to anticipate

  • 7/29/2019 Cpp Latest Me

    106/114

    106

    In some situations, we may not be able to anticipate

    all possible types of exceptions and therefore may not

    be able to design independent catch handlers to catchthem. In such situations, we can force a catch

    statement to catch all exceptions instead of a certain

    type alone. This can be achieved by defining the catchstatement using ellipses.

    catch()

    { //all exceptions }

    Note: catch() should always be placed last in the list

    of handlers.

    This pointer:If p is an object of class sample and get() is a member

  • 7/29/2019 Cpp Latest Me

    107/114

    107

    If p is an object of class sample and get() is a member

    function of sample, the statement p.get() us used to

    call that function. The statement p.get() operates onp. in the same way if ptr is a pointer to p object, the

    function called ptr -> get() operates on *ptr.

    C++ compiler provides get() with a pointer to p calledthis. The pointer this is transferred as an unseen

    parameter in all calls to non-static member functions.

    The key word this is a local variable that is always

    present in the body of any non-static member

    function.

    Operators new and new[]In order to request dynamic memory we use the operator

  • 7/29/2019 Cpp Latest Me

    108/114

    108

    q y y p

    new. new is followed by a data type specifier.

    If a sequence of more than one element is required- thenumber of these within brackets [].

    It returns a pointer to the beginning of the new block of

    memory allocated. Its form is:

    pointer = new typepointer = new type [no_of_elements]

    The first expression is used to allocate memory to contain

    one single element of type type. The second one is usedto assign a block (an array) of elements.

    Operator delete and delete[]Since the necessity of dynamic memory is usually

  • 7/29/2019 Cpp Latest Me

    109/114

    109

    y y y y

    limited to specific moments within a program, once it

    is no longer needed it should be freed so that thememory becomes available again for other requests

    of dynamic memory. This is the purpose of the

    operator delete, whose format is:

    delete pointer;

    delete [] pointer;

    The first expression should be used to delete memory

    allocated for a single element, and the second one for

    memory allocated for arrays of elements.

    Advantages of new over malloc():1. It automatically computes the size of the data object. We

  • 7/29/2019 Cpp Latest Me

    110/114

    110

    need not use the operator sizeof.

    2. It automatically returns the correct pointer type, so that

    there is not need to use a type cast.

    3. It is possible to initialize the object while creating the

    memory space.

    4. Like any other operator, new and delete can be

    overloaded.

    Dynamic constructors:

  • 7/29/2019 Cpp Latest Me

    111/114

    111

    The constructors can also be used to allocate

    memory while creating objects. This will enable thesystem to allocate the right amount of memory for

    each object when the objects are not of the same

    size, thus resulting in the saving of memory.

    Allocation of memory to objects at the time of their

    construction is called dynamic construction of objects.

    Virtual functions:Virtual functions of base classes must be

  • 7/29/2019 Cpp Latest Me

    112/114

    112

    redefined in the derived classes. The programmer can

    define a virtual function in a base class and can usethe same function name in any derived class, even if

    the number and type of arguments are matching. The

    matching function overrides the base class function of

    the same name. virtual functions can only be member

    functions.

    Rules for Virtual functions:1. The virtual function should not be static and must be a

  • 7/29/2019 Cpp Latest Me

    113/114

    113

    member class.

    2. A virtual function may be declared as friend foranother class.

    3. Constructors can not be declared as virtual, but

    destructors can be.

    4. The virtual function must be defined in public sectionof the class.

    5. The prototype of virtual function in base and derived

    classes should be exactly the same. In case ofmismatch, the compiler neglects the virtual function

    mechanism and treats them as overloaded functions.

    Pure virtual functions:A pure virtual function is a function declared in a base

  • 7/29/2019 Cpp Latest Me

    114/114

    class that has no definition relative to the base class. In

    such cases, the compiler requires each derived classeither define the function or redeclare it as a pure virtual

    function. A class containing pure virtual functions cannot

    be used to declare any objects of its own. Such classes are

    called abstract base classes. The main objective of anabstract base class is to provide some traits to the derived

    classes and to create a base pointer required for

    achieving run time polymorphism.

    Ex: