Lecture_Notes_COMP 116, Class Note

Embed Size (px)

Citation preview

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    1/74

    COMP 116: OBJECT ORINENTED PROGRAMMING

    Introduction to Object Oriented Programming [4 hours]

    o Concept of Object Oriented Paradigmo Features of OOPo Benefits of OOP

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    2/74

    CHAPTER-1

    Introduction to Object Oriented Programming

    1.1 Concept of Object Oriented Paradigm:

    Private access:-It implies that the members can be accessed only by the other members of the class.

    Public access:-It implies that the members can be accessed directly by other members of the class and by objects

    (at main function) of the class using dot (.) operators.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    3/74

    1.2 FEATURES OF OOP

    1. Object2. Class3. Abstraction4. Encapsulation5. Inheritance6. Polymorphism7. Data hiding / Information hiding

    1. Object:Objects are said to be members/instancesfor classes. We can define many objects of the

    same class. Class and their objects can be defined according to the problem at hand.

    e.g.: Animal is a class and cat, dog, lion, tiger objects of class animal.

    2. Class:A class is a data type defined by the user describing the data it represents and the function

    to be used to manipulate the data. It seems as a plan/template/blue print.

    3. Abstraction: It is a process that involves identifying the critical behavior of an object and elimination

    irrelevant and complex details. It must be simple and easy to use in the perspective of the

    user.

    4. Encapsulation: It is a method for protecting data from unwanted access of alteration by packing it in an

    object, where it is only accessible through objects interface. In encapsulation definition of an

    object and various functions for communicating with other objects can be fit into together.

    5. Inheritance:It is used to model the usual features in real world, which will allow a programmer to

    reuse and share data as well as code. In other words, each subclass (derived class) shares

    common characteristics with the class (base class) form which it has been derived. In addition

    to the characteristics shared with others members of the class, each sub-class has its own

    particular characteristics.

    6. Polymorphism:Using operators and functions in different ways, depending on what they are

    operating on, are called polymorphism (1 thing with several distinct forms). In other words,

    getting different meanings of the same thing or multi-use from one is called polymorphism.

    Overloading is kind of polymorphism.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    4/74

    7. Data hiding/ Information hiding:Different data/ functions can be protected from unauthorized access i.e. data and

    functions can be kept secret. It is the result of Encapsulation, in which data and function can

    be bounded inside a class.

    1.3 BENEFITS OF OOP

    Some important benefits of OOP are:-

    1. We can eliminate redundant codes and extend the use of existing classes through inheritance.2. Saving development time and higher productivity can be achieved by building program form

    the standard working modules.

    3. We can build secure program by using data hiding principle.4. Multiple instances of an object co-exist without any interference.5. It helps to solve real world problem accurately by mapping objects in the problem domain to

    those in the program.

    6. It is easy to partition the work in a project based on object.7. It helps to capture more details of a model in implementable form.8. System can be easily upgraded from small to large system.9. Software complexity can be easily managed.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    5/74

    Introducing C++ [4 hours]

    o Introductiono A sample C++ programo Reference Variableso Inline Functionso Function Overloadingo Comparison between C and C++

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    6/74

    CHAPTER-2

    Introducing C++

    2.1 A sample C++ program

    //simple example to show the class and object to use in the C++

    //myclass1.cpp

    #include

    using namespace std;

    class myclass1 //myclass1 is name of class

    {

    private: //access type

    int num;

    public: //access type

    void getdata ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    7/74

    2.1 Reference variables:

    A variable which provides an alias (alterative name) or previously defend variable is known as

    reference variable. It must be initialized at the time of declaration.

    e.g. int total = 1000;int & sum =total; //reference to int

    In this example, sum is alias of total and both reference to same data object (i.e., 1000) in the

    memory.

    Its main application is in passing arguments to function. In addition, it permits the

    manipulation of objects by reference and eliminates the copying of objects parameters back and forth.

    //sum (int a,int b)

    The references can be created for both built-in data type and user defined data type.

    2.3 Inline-Function:

    An Inline function requests(not commands) the compiler to replace the function call with the

    corresponding function code. In other words, this function is compiled into inline code instead

    of into a function.

    e.g. inline int cube(int a)

    {

    return (a*a*a);

    }

    We can invoke above inline function as below:

    main ( )

    {

    int c;

    c=cube (3); //above statements are inserted here when the function is called

    Inline function eliminates cost of calls to small functions (say 2/3 lines).

    2.4 Inline expansion may not work in the following situations:

    1. For functions retuning values, if a loop, a switch or a go to exists.2. For functions not returning values, if a return statement exists.3. If functions contain static variables.4. If inline functions are recursive.

    2.5 Function Overloading:

    When two or more functions have the same name wit different function definition for each

    but with different set of arguments (i.e., different number or/and types of argument list). It is

    known as function overloading/function polymorphism. By overloading a function, we can

    types of the arguments determine the invocation of the correct function.

    Parameters/arguments

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    8/74

    2.5.1 //illustration of function overoading

    #include

    using namespace std;

    inline int AreaRect(int x, int y){

    return (x*y);

    }

    inline float AreaRect(float p,float q)

    {

    return p*q;

    }

    int main( )

    {

    int a=10;int b=5;

    float c=2.5;

    float d=2.6;

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    9/74

    {

    for(int j=0;j

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    10/74

    Classes and Objects [6 hours]

    o Introduction to class and objectso Defining a class with member functiono Private Member Functionso Initializing an Objecto Static Data Memberso Static Member Functions

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    11/74

    CHATER-3

    Classes and Objects

    3.1 Introduction to class and objects:

    1. Object:Objects are said to be members/instances for classes. We can define many objects of

    the same class. Class and their objects can be defined according to the problem at hand.

    e.g.: Animal is a class and cat, dog, lion, tiger objects of class animal.

    2. Class:A class is a data type defined by the user describing the data it represents and the

    function to be used to manipulate the data. It seems as aplan/template/blue print.

    3.3 Private Member Functions:

    A private member function can only be called by another function i.e. member

    function that is a function of its class. Even an object can not invoke a private function using

    the dot (.) operator.

    e.g.:

    class sample

    {

    int m;

    void read(void);

    public:

    void update( );

    void write( );

    };

    If s1 is an object of sample (class) then

    s1.read ( ); // is illegal and will no work because object can not access the private member

    function.

    But the function read ( ) can be called by the function update ( ) to update the value of

    mand/ or by the function write ( ) to write the valued of m.

    void sample : : update (void)

    {

    read ( );//simple call without using object

    }

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    12/74

    3.4 Static Data Members:

    Each object in a class has its own separate data. If all the objects need to share one

    data, a slight change in the class specification would be sufficient. The modification required

    would be to give a keyword staticfor the data which is to be shared. If a data item in a

    class is defined as static, then only one such item is created for the entire class, no matter how

    many objects are there. A member variable defined as static hassimilar characteristics to a

    normal static variable. It is visible only within the class, but its lifetime is the entire program.

    Some compilers automatically initialize a static data item, where other does not.

    3.5 Static Member Function:

    A static member function is one which can be called directly form main ( ) without

    associating it to an object. In other words a static member function can be called withoutcreating instances / objects of the class.

    3.5.1Example of static data member

    #include

    using namespace std;

    class my

    {

    static int count; //declaration of one data item for all objects

    public:

    my ( ){

    count ++;

    }

    int getcount ( )

    {

    return count;

    }

    };

    int my::count = 0; // definition of count which alloates memory for count, and initializes it

    int main ( )

    {

    my f1,f2,f3;

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    13/74

    count is 3

    count is 3

    3.5.2 //example of static data member

    #include

    using namespace std;

    class my

    {

    private:

    int id;

    static int tot;

    public:

    my ( )

    {

    tot ++;

    id = tot;}

    void print( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    14/74

    Object Constructor and Destructions [5 hours]

    o Introduction Constructoro Parameterized Constructoro Copy Constructoro Destructor

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    15/74

    CHAPTER-4

    Object Constructions and Destructions

    4.1 Introduction to Constructor:

    A constructor is a member function (manager function) that is executed automatically

    whenever an object is created. In other words a constructor is special member function due to

    which automatic initialization is carried out (f an object). It is a convenient way to initialize

    an object when it is first created without the need to make a separate call to a member

    function. Constructors may or may not take arguments depending how the object is to beconstructed; there is no return value from the constructors.

    A constructor always as the same name as the class it-self. Every class has an implicit

    constructor which ne not b defined. It is called automatically for the object as it is created.

    4.1.1 sample program of constructor

    #include

    using namespace std;

    class integer

    {

    int m,n;

    public:

    integer (int, int);

    void display(void)

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    16/74

    return 0;

    }

    Output:

    OBJECT 1

    m=0

    n=100

    OBJECT

    m=25

    n=75

    4.2 Parameterized Constructors:

    The constructors that can take arguments are called parameterized constructors. Thisfeature in C++ initializes the various data members of different objects with different values

    (instead of initialization of the data members of all objects to zero) when they are created.

    e.g.

    class myclass

    {

    int m,n;

    public:

    myclass (int x,int y); //parameterizedconstructor

    .

    .

    .

    };

    int main( )

    {

    myclass c1;// may not work

    myclass c2(20,40);//implicit

    }

    Constructor function can be defined as inline function. Parameters of a constructor can be of any type except that of the class to which it

    belong

    e.g. class X

    {

    .

    .

    public:

    X (X);//class X as a parameter is illegal

    };

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    17/74

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    18/74

    However, a constructor can accept a reference to its on class as a parameter

    class X

    {

    public:

    X (X&);//reference of class X as a parameter.

    This constructor is called copy constructor.

    4.3 Copy constructor:

    A copy constructor is used to declare and initialize an object fro another object. A

    reference variable is used as an argument to the copy constructor. We can not pass the

    argument by value to a copy constructor, this is because when an argument is passed byvalue, a copy of it is constructed i.e. a copy constructor is constructed. S it calls itself over

    and over until the compiler runs out of memory. So, in the copy constructor the argument

    must be passed by reference which creates no copies.

    e.g. if the class name is alpha

    alpha a1;//object created for class alpha

    alpha a3 (a1); //copy initialization i.e. object a3 is defined and at the sae time it is

    initialized to the values of a1

    alpha a3=a1;//alternate syntax

    alpha (alpha &a1);//copy constructor

    To initialize an object at class alphaalpha a1;//default constructor will be called

    alpha a2 (100);//default constructor will be called

    alpha a1;//default constructor will be called

    alpha a2 (a1);// a member wise cop take place

    or

    alpha a2=a1;// a member wise cop take place

    To prevent this member wise copy it is necessary to provide the copy constructor. The member wise copy which the compiler does is dangerous if the object contains

    pointer.

    e.g.

    class alpha

    {

    private:

    char *myname;

    public:

    alpha( )

    {strcpy (myclass, \0);

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    19/74

    };

    alpha a1;

    creates object a1, with a pointer named myname pointing at a memory location (x), which is copied

    from a1.

    Due to the member wise copy, both objects have pointers pointing at the same memory location,

    resulting in one object being dependent on the other. Therefore, it is necessary to provide copy

    constructor in this class.

    4.4 Destructor:

    This is activated when the object is destroyed automatically when the program ends

    of when the program controls passes to a statement outside the cope of the object. A

    destructor has the same name as the class preceded by a tilde (~) e.g. ~counter ( ). Destructors

    also have no return values. They take no arguments. Therefore it can not be overloaded. Like

    constructor destructor is also a special member function. The use of these functions is to freememory allocated for the object by the constructor.

    For example, if an object is used as local variable in a function, the destructor is

    invoked when the compiler returns to the calling procedure.

    An object can be destroyed only when the resources of the object is free i.e. first

    member elements associated with object should be destroyed then only object will e destroyed

    by the destructor. Otherwise system will crash. Therefore before destroying an object, the

    resources associated with the object most be destroyed, so we explicitly call destructor to

    destroy resources occupied by the object (a default destructor only destroys object but notresources).

    Since, constructors and destructors will not be robust enough for our class we should

    provide our own version of them.

    They can not have return value (not even void). Pointers and references can not be used on them (it is not possible to get their

    address).

    They can not be declared static, constants or volatile. They can not be declared with the keyword virtual.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    20/74

    4.4.1 //sample program to illustrate destructor

    #include

    using namespace std;class myclass

    {

    int num;

    public:

    myclass( ) // default constructor

    {

    num=0;

    }

    myclass (int n) //overload constructor

    {num=n;

    }

    ~ myclass ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    21/74

    Object destroyed!

    Object destroyed!

    4.4.2 //sample program of parameterized constructor

    #include

    using namespace std;class mypc

    {

    int m,n;

    public:

    mypc (int, int); //constructor declared

    void display ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    22/74

    4.4.3 //example for copy constructor

    #include

    using namespace std;

    class alpha

    {int id;

    public:

    alpha( ){ }//constructor

    alpha (int a)

    {

    id = a;

    }

    alpha (alpha &x) //copy construtor

    {

    id = x.id;}

    void display(void)

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    23/74

    4.4.4 //example for copy constructor

    #include

    using namespace std;

    class alpha

    {

    int data;

    public:

    alpha( ){ }//constructor

    alpha (int d)

    {

    data = d;

    }

    alpha (alpha &a) //copy construtor

    {data = a.data;

    }

    void display( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    24/74

    Operator Overloading [6 hours]

    o Introductiono Defining Operator Overloadingo Overloading Unary Operatorso Overloading Binary Operatorso Overloading Binary Operators using Friend Functions

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    25/74

    CHAPTER-5

    Operator Overloading

    5.1 Introduction:

    Normally,

    a= b + c;

    works with basic data types such as int and float, attempting to apply it when a, b and c

    are objects of a user defined class will cause complaint from compiler. However using

    overloading we can make this statement legal even when a, b and c are user- defined types.

    C++ has an ability to provide the operators with a special meaning for a data type. The

    mechanism of giving such special meanings to an operator is known s operator

    overloading.

    Operator overloading gives us the opportunity to redefine the C++ language within a class. If

    we find ourselves limited by the way the C++ operators work, we can change tem to do

    whatever we want. By using classes to create new kings of variables, and operator

    overloading to create new definition for operator, we can extend C++ to be a new language

    for our own design. Another kind of operation, Data conversion, is closely connected withoperator overloading in C++. C++ handles the conversion of simple types like int and float

    automatically, but conversions involving user-defined types require some work on the

    programmers part. When an operator is overloaded, its original meaning is not lost.

    5.2 Defining operator overloading:

    C++ program can overload existing operators with some others operations. If the

    operator is not used in the context as defined by the language, then the overloaded operator if

    defined will be executed. Overloaded operators are those that have been re-defined within a

    C++ class using the keyword operator followed by an operator symbol.

    All operators can be overloaded except:class member access operator (. , .*)

    scope resolution operator (: :)

    size operator (size of)

    conditional operator (? :)

    pre-processor symbols (#, ##)

    The term operator overloading refers to giving the primitive C+++ operator additional

    functionality when they are applied to user defined data types.

    The general form of an operator overloading is:return_type classname : : operator op(argument list) //here opis +,

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    26/74

    {

    function body;// task defined

    }

    Where return type is the type of the value returned by the specified operator opis the operator

    being overloaded and operator preceding opis the keyword.

    5.3 Overloading Unary Operators:

    Unary operators act on only one operand (an operand is simply a variable acted on by

    an operator). Examples of unary operators are the increment and decrement operators (++, --)

    and the unary minus (-), as in (-20).

    The syntax of overloading is:

    return_type operator unary operator (arguments

    {

    function body;

    }int operator ++( )

    {

    .

    .

    }

    5.3.1 Limitations of Increment operator:

    When applied to basic data types prefix and post fix operators are two different

    operators. But when they are overloaded there is no distinction (difference) between prefix

    and post fix notation. The expression c2=c1++ has exactly the same effect as c2=++c1. Inboth cases c1 is assigned to c2. If we need the basic data type incrimination for the

    overloaded function, then it requires two overloaded operators, one for prefix and one for post

    fix.

    operator ++ ( );//prefix

    operator ++ (int );//post fix

    The second declaration uses a dummy int argument, which is said to zero automatically by

    the post fix (++) operator. This extra argument allows the compiler to distinguish the two

    forms.

    Note:Unary operator act at only one operand. An overloaded operator always

    requires one less argument than its number of operands is the object of which the

    operator is a member function. Hence, unary operator requires no argument/s.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    27/74

    5.3.2//sample program of unary operator( ) overloading

    #include

    using namespace std;class space

    {

    int x,y,z;

    public:

    void getdata (int a, int b, int c);

    void display (void );

    void operator -( );//overloaded unary minus operator

    };

    void space::getdata (int a, int b, int c){

    x=a;

    y=b;

    z=c;

    }

    void space::display(void)

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    28/74

    s= 100,-200,-300

    s= -100, 200, 300

    5.3.3 //increment counter variable with ++ operator

    #include

    using namespace std;class counter

    {

    int count;

    public:

    counter( )

    {

    count = 0;

    }

    int getcount ( )

    {return count;

    }

    void operator ++ ( ) // tells compiler to call this member funciton whenever te ++

    operator is encountered, provided the operand is of type

    conter, ++ overloaded

    {

    ++ count;

    }

    };

    int main( )

    {

    counter c1,c2; //defined and initialized

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    29/74

    5.3.4 //example to increment counter variable with ++ operator

    #include

    using namespace std;

    class counter

    {int count;

    public:

    counter( )

    {

    count = 0;

    }

    int getcount( )

    {

    return count;

    }counter operator ++ ( )

    {

    count ++;

    counter temp;

    temp.count = count;

    return temp;

    }

    };

    int main( )

    {

    counter c1,c2;

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    30/74

    5.4 Overloading Binary Operator:

    Binary operator s act on tow operands. Example of binary operators are arithmetic

    operators (+, -, *, /, %), relational operator (=, >,=,

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    31/74

    void getdist ( )

    {

    coutfeet;

    coutinches;

    }

    void showdist ( ) const

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    32/74

    5.4.2 //example of

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    33/74

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    34/74

    5.4 Overloading Binary Operator Using Friend Function:

    Like member function (non-static), friend functions can also be used to overload

    binary operators. But friend functions require one argument for unary operator and two

    arguments for binary operator arguments may be passed either by value or reference.

    The declaration of binary operators using friend function is:

    fr iend class name operator op (class name obj, class name obj);

    We can use a friend function with a built-in type data as the left-hand operand and an

    object as the right hand operand, whereas in the case of member function the left hand

    operand must be an object of the class which is responsible to invoke (call) the overloaded

    member function.

    Therefore, when we need to use two different types of operands for a binary operatorwe can use friend function to overload the operator.

    Hence, below statement will not work for a member function but for a friend function

    A= 2+B of 2*B

    where A and B are objects of the class and 2 is built in data type.

    We can not use friend function to overload following operators:

    1. Assignment operator (=)2. Function call operator [ ( ) ]3. Subscripting operator ( [ ] )4. Class member access operator (->)

    However, these operators can be overloaded by using member functions.

    5.4.1 //example for binary operator + using friend function

    #include

    using namespace std;

    class complex

    {

    int real;int img;

    public:

    complex ( )

    {}

    complex (int a,int b)

    {

    real=a;img=b;

    }

    void showdata ( )

    {cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    35/74

    }

    friend complex operator + (complex a, complex b);

    };

    complex operator + (complex a, complex b)

    {

    return complex ((a.real+b.real),(a.img+b.img));

    }

    int main()

    {

    complex c1,c2,c3;

    c1=complex (5,10);

    c2=complex (15,20);

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    36/74

    Inheritance [6 hours]

    o Introductiono Base Classes and Derived Classeso Single Inheritance and Multiple Inheritanceo Protected Members

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    37/74

    CHAPTER-6

    Inheritance

    6.1 Introduction:

    The one of the most important feature of OOP, to allow the reusability of code and

    data that already exists is known as inheritance. By the help this feature the C++ classes can

    be reused in several ways. Once a class has been written and tested, it can be adapted by other

    programmers to suit their requirements. This is basically done by creating new classes,

    reusing the properties of the existing ones. The old class is referred as the base classand the

    new one is called the der ived classor subclass.

    The derived class inherits all the capabilities / features of the base class along with

    adding properties of its own. The base class is unchanged by this process. Inheritance

    mechanism permits data sharing and code reusability, i.e. data and code in a g9gher level

    class can be shared and reused in any class which is inherited from that class. This reduces

    debugging cost, enables easy maintenance and modification, and provides easy design for

    large software system and so on.

    General syntax for class derivation is as follows:

    class D: B

    {

    Body of the class D;

    }

    where D stands for derived class and B for base class.

    There are three types of class specifier:

    i. Publicii. Private

    iii. Protectede.g.:

    class D: public B

    {

    }

    Where class D is publicly derived from class B

    Access specifiers determine the availability of the base class members to derived class.

    Note:By default a sub class is privately derived from a base class

    e.g.:

    class D: B//private derivation by default

    {

    ..;}

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    38/74

    6.2 Base Class and Derived Class:

    Base Class:The parent class or the old class from which data or code are inherited.

    Derived Class:The child class of the subclass in which data or code are inherited to reuse.

    6.3 The types of inheritance:

    1. Single inheritanceIt means a derived class with only one base class. Here, B is base class and D is only

    one derived class.

    2. Multiple inheritanceIt means a derived class from two or more different base classes. Here B1, B2 B-n

    are different base classes and D is derived class. Syntax for multiple inheritance

    class B1//Base class

    {

    ..

    };

    class B2 //Base class

    {

    ..

    };

    class D: public B1, public B2 // D is derived class

    The base classes from which D is derived are listed following column in Dsspecification. The base classes are separated by comma ( , ).

    ..

    B

    D

    B-nB1

    D

    B2

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    39/74

    3. Hierarchical inheritanceIt means many derived classes from a single base class. Here B is a base class and

    D1, D2..D-n are different derived classes.

    4. Multi-level inheritanceIn this type of inheritance step wise derivation is done. Here, B is base class D is

    derived class and C is the derived class from D.

    5. Hybrid inheritanceThis inheritance allows to derive different derived classes and one derived class from

    these derived class. Here, B is base class and D1 and D2 are derived class then C is

    the final derived class from D1 and D2.

    B

    D1 D2

    C

    B

    D

    C

    D1

    B

    D2 D-n

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    40/74

    The derived class inherits access attributes from a base class as follows:

    1. Public base access:If the access modifier is public then public and protected member of the vase class arethe public and protected members respectively in the derived class.

    i.e. class D: public B

    private members of the base class remain private to the base i.e. they are not

    accessible in the derived class.

    2. Private base access:Public and protected members of the base class are private members of the derived

    class, i.e. they are not accessible to any class which is derived fro this second class.

    3. Protected base access:All non-private members become the protected members in the derived class. Private

    members are not accessible in the derived class.

    Table: Showing the difference among the three access specifiers.

    Access specifier Access specifier in Base

    class

    Inherited Access in derived

    class

    Public

    Class D : public B

    Public Public

    Private Not accessible

    Protected Protected

    private

    Class D : private B

    Public Private

    Private Not accessible

    Protected Private

    protectedClass D : protected B

    Public Protected

    Private Not accessible

    Protected Protected

    Table: Access specifiers.

    Accessspecifiers

    Accesible fromown class

    Accessible formderived class

    Accessible from objectsoutside class

    Public Yes Yes Yes

    Private Yes No No

    Protected Yes Yes No

    Even if other classes have been derived from it, the base class remains unchanged.

    The base class objects can not use any data members or member function of the derived

    function.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    41/74

    Accessing base class members:A member function in the base class can be used by objects of the derived

    class, this is called accessibility. This can be done by two ways.

    i. Substituting base class constructorsii. Substituting base class member function Note:

    1) When 2 or more base classes have same function (e.g. display ( ), function) we use classresolution operator with the function to use the display( ) function of particular base class

    and it removes ambiguity in inheritance.

    e.g. If base classes B and B2 have function display ( ) we use B1:: display( ); and B2::

    display ( ). To use the respective display ( ) function of the base classes.

    2) If base class and derived class have same function name, the function of the derived classover-rides together the inherited function in the base class

    //sample program

    #include

    using namespace std;

    class B

    {

    public:void display ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    42/74

    Output:

    I learned C

    I am learning C++

    I learned C

    6.4 Protected Members:

    Protected members are private within a class and available for private access in the

    derived class (i.e. they are accessible by using member function but not using objects. We

    specify data members as protected whenever we would like to share private members with

    derived class because private members can not be accessed outside the class. Therefore the

    access specifier protected provides a mechanism to share private members of a class with its

    derived class / classes.Protected members are considerably less secure than private members because they

    are accessible simply by deriving other classes from the class with protected members to

    avoid corrupted data. It is often safe to force derive class to access data in base class using

    only public member function of the base class.

    6.4.1 //example to show single inheritance

    #include

    using namespace std;

    class counter

    {

    protected:

    int count;

    public:

    counter ( ):count(0)

    {}

    counter (int c):count (c)

    {}

    int getcount()

    {

    return count;

    }

    counter operator ++ ( )

    {

    return counter (++ count);

    }

    };

    class D: public counter //derived class

    {

    public:

    counter operator - - ( )

    {return counter(--count);

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    43/74

    }

    };

    int main ( )

    {

    D c1;

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    44/74

    void mom::getincome(int b)

    {

    income = b;

    }

    void child::display ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    45/74

    In multiple inheritance, consider a base class Boss, to derive classes manaager1 and

    manager2, and a fourth class, sub-ordinate, derived from manager1 and manager2. In this scenario if

    a compiler error (ambiguous) occurs. Since, the manager1 and manager2 classes are derived fro Boss,

    each inherits a copy (i.e. sub-object) of Boss and each of the two sub-objects contains its own copy of

    Boss data or function. When member (data of function) belonging to boss is referred in sub-ordinate

    the referred member is simultaneously present both in manager1 and mnager2. This will create an

    ambiguity in sub-ordinate class on deciding which of the two copies of referred member will it accessto resolve such type of virtual base class declaration. Hence in above example we make manager1 and

    manager2 in virtual base classes.

    //virtual base class

    class Boss

    {

    protected:

    int base data;

    };

    class manager1 : virtual public Boss // shares copy at Boss

    { };

    class manager2 :: virtual public Boss // shares copy at Boss

    { };

    class subordinate : public manager 1, public manager2

    {

    public:

    int getdata ( );

    {

    Return base data;// OK: only one copy of parent

    }

    };

    By using keyword virtual in base classes only single copy (i.e. sub-object) of member will

    inherit, instead of multiple copy, and base classes, share a single common sub-object without

    occurring ambiguity.

    NoteI. Public and virtual can be inter-changed and used.

    II. What would happen when multiple inheritance includes both public andprivate derivation of virtual base class i.e.

    class manager1:public virtual Bossclass manager1:public virtual Boss

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    46/74

    class sub-ordinate : public manager1, public manager2

    If there are both public and private paths then public path will dominate i.e. the referred

    member is Boss class are accessible to sub-ordinate class.

    Constructors and destructors in Base classes (class initialization in inheritance). When a class

    D inherits fro B, then initialization of D requires the initialization of B as well. This is why the

    constructor in class D should be adjusted accordingly.

    RULE 1

    When a base class and derived class both have their own construction, then the constructor forthe base class is invoked first; after the completion of this task successfully the constructor of derived

    class is invoked. Thus in the following case.

    B < D < .. D1 call a constructor is B ( ), D ( ) & D1 ( ) in this order.

    RULE 2 In the case of multiple inheritance when more than one base class is invoked the base class

    constructors are order they are declared. Thus on class

    D, B1, B2 { D ( ) }; constructors invoked and B1 ( ), B2 ( ) and D ( )

    class D1 : B1

    class D2 : B2

    class D : D1, D2 { }

    RULE 3

    Constructors for virtual base classes are invoked before any non-virtual baseclasses.

    e.g.: class : public Y, virtual Z { };

    constructor will be invoked as Z ( ), Y ( ), X ( )

    RULE 4

    If the hierarchy contain s multiple virtual base classes, then the virtual base classconstructors are invoked in the order in which they are declared any non-virtual base class constructor

    are then invoked before the derived class constructor is called. E.g.: In the case of

    class D : virtual M, virtual N, public o, virtual P, public Q

    constructor will be invoked as M ( ), N ( ), O ( ), Q ( ), D ( )

    B-nB1

    D

    B2

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    47/74

    6.5.2.1 //sample program to virtual base class

    #include

    using namespace std;

    class student{

    protected:

    int rollno;

    public:

    void getnum(int a)

    {

    rollno=a;

    }

    void putnum ( )

    {cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    48/74

    };

    class result : public exam, public sports

    {

    float total;

    public:

    void display ( );

    };

    void result::display ( )

    {

    total = part1+part2+score;

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    49/74

    6.5.2.2 //sample program to class inheritance

    #include

    using namespace std;class alpha

    {

    int X;

    public:

    alpha (int i)

    {

    X=1;

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    50/74

    }

    };

    int main ( )

    {

    gamma g(10,20.5,30,40);

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    51/74

    Arguments for the base classWhen both base class and derived class constructors have their own arguments, how the

    appropriate argument be passed to the right constructor.

    RULE

    To initialize the member elements in the base class the arguments required should be passed

    through an object of derived class.

    Suppose constructors in the base class and derived class require the following list of arguments.

    Base class : (arg1, arg2, .. argm)

    Derived class : ( arg1,arg2, .. argn)

    Then argument should be passed as below:

    Derived class obj (arg1, arg2, .. argm,arg1, arg2, .. argn)

    i.e. all the arguments of base class first, then the argument of the right class should be passed

    e.g.:

    class B

    {

    ..

    B (int a, float b)

    ..

    };

    Class D: B

    {

    ..

    D (int a, float b, char *z); // first two arguments for B class and last one for D

    ..

    };

    The constructor D ( will be appeared as

    D::D (int a, float b, char *z) : B (a , b) //B (a , b) means a and b arguments are for base class

    constructor

    {

    ..

    Body of D

    ..

    };

    NoteDestructors in base classes and derived classes are invoked in reverse (opposite) order as do

    constructors invoked in them.

    i.e. first the destructor of derived class is invoked and then the destructor of base class invokes.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    52/74

    Polymorphism [6 hours]

    o Introductiono Pointers to Objectso Pointers to Derived Classeso Virtual Functionso Pure Virtual Functions

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    53/74

    CHAPTER-7Polymorphism

    7.1Introduction:Polymorphism means the same thing but in different forms. In C++ the meaning of

    polymorphism is the ability to access different implementations of a function using the

    same name.

    There is to levels at which polymorphism operates:

    i. Compile time polymorphism:It is achieved through operator overloading and function overloading. In this

    type of polymorphism and object is bound to its function call at compile time

    polymorphism. Also it6kr` is known as early binding of static binding of static

    linking.

    ii. Run time polymorphism:In this polymorphism function is linked with a particular class much later

    after the compilation and the selection of appropriate function is done

    dynamically at run time therefore this type of polymorphism is also known as late

    binding or dynamic binding.

    Fig: types of polymorphism

    6.2 Pointers to Objects

    A pointer can point to an object created b a class suppose that sd1 is an object of class

    student as : student sd1;

    Object pointer ptr of type student can be created as belowstudent sd1;

    Polymorphism

    Compile time

    polymorphism

    Run time

    polymorphism

    Operator

    overloadingVirtual function

    Function

    overloading

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    54/74

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    55/74

    b num = 5[phe0; c num = 100; d num = 200;

    bp - > bnum = 50; //OK cp - > cnum = 100; //OK dp - > dnum = 200; //OK

    bp - > cnum = 100; // wontwork

    cp - > bnum = 50; // wontwork

    dp - > bnum = 50; // wont work

    bp - > dnum = 200; // wontwork

    cp - > dnum = 200; // wontwork

    dp - > cnum = 150; // wontwork

    6.4 Virtual Function:

    Existing in appearance but not in reality. Virtual functions are needed to perform a particular operation using the same function call

    by objects of different classes.

    e.g. By using a single draw function we can draw different shapes, circle, rectangle, triangle

    and so on. For this, object of different classes are used t call the same function.

    For dynamic binding of member functions, C++ uses the concept of virtual function. Virtual functions are the functions which are declared with the keyword virtual in the base

    class e.g. virtual void dispdata ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    56/74

    b. All re-definition of functions in derived classes are treated as virtual provided they match thebase class function precisely (exactly) in terms of the member and types of argument passed.

    If they do not match exactly then they will be treated as ordinary overloaded function.

    c. A virtual function in a base class may or may not be defined. If they are not defined then theymust be declared as pure.

    6.5 Pure Virtual Functions:

    A pure virtual function is one with the expression = 0 (zero not o) added to the

    declaration in other words a pure virtual function is one which is declared with a keyword

    virtual and initialize to zero. The = 0 syntax is simply how we tell the compiler that a

    virtual function will be pure. The = sign here, has nothing to do with assignment, the value

    zero is not assigned to anything. A pure virtual function can be declared as pure by any of the

    following ways:

    a) virtual () = 0;b) virtual ()c) {

    . ;

    }

    d) virtual void show () -0; //pure virtual function;A pure virtual function does not contain any effective code i.e. there is no

    implementation of function within the class where the function was declared. It provides an

    interface for the class hierarchy.

    Abstract Classes:An abstract class is a class with at least one pure virtual function. Objects of an

    abstract class can not e defined, but they are used to derive child class. A pointer to abstract

    class can be derived.

    e.g. the following class Abstract X is an abstract class

    class Abstract X{

    public:

    void function1 ( );

    virtual void vf1 ( ) = 0;

    virtual void vf2 ( ) =0;

    };

    Notes:a. An abstract class can be used as base class only for other classes. No object of an abstract

    class can be declared.

    Abstract class // illegalAbstract X x; //attempt to create an object of the abstract class

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    57/74

    b. An abstract class can not be specified as an argument type or as a function return type.int abs1 (Abstract X x);// X being an abstract class, can not pass anything to the function

    Abstract X abs2 (int i); //Error- nothing can be returned to an Abstract Xs object i.e.

    object of an abstract class is not possible to hold any value.

    c. Member functions in an abstract class may be called from a constructor of abstract classbut calling pure virtual function either directly or in directly form such a constructor

    provokes run time error.

    Abstract X ( )// constructor

    {

    vf2 ( );//error-direct call of vf2 which is a pure virtual function

    }

    void configuration ( )

    {

    vf2 ( );// error- indirect call of vf2 which is a pure virtual function

    d. The actual use of declaring a class as an abstract class is to implement the dynamicbinding in C++. An abstract class is always a base class and contains member function/s

    as pure virtual function which resolves the reference of the function name dynamically in

    later derived classes.

    6.5.1 //sample program accessed from pointer

    #include

    using namespace std;

    class Base

    {

    public:

    void show ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    58/74

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    59/74

    class Derive1 : public Base

    {

    public:void show ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    60/74

    In binary operator overloading using function we pass only one argument to the function andother argument is implicitly to the function and other argument is implicitly passed using

    this pointer.

    One application of this pointer is to return the object it point to we use following statements.Inside a member function to return the object that invoke the function.

    Return *this;

    Memory management in C++

    When an array is defined the complier sets aside memory for the array data. Array are

    useful source for data storage, but they have a serious drawback, because we have to know in

    advance how much data will be stored and declare an array of that size. This is because

    compiler requires the array size to be constant. IN such case we can define large arrays but

    there will be wastage of space. To overcome this C++ has two operators.

    They are:

    a. newallocates memoryb. deletede-allocates memory

    The new operator

    This operator obtains memory from operating system and returns a pointer to its

    starting point. This operator returns pointer to appropriate type without casting.

    The delete operator

    This operator de-allocates the memory allocated to the pointer variable. If the

    program resolves many chunks of memory using new operator eventually all the available

    memory will be resolved and the system will crash to ensure safe and efficient use of memory

    the new operator should be matched to operating system.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    61/74

    Template [4 hours]

    o Introductiono Class Templateso Function Templates

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    62/74

    CHAPTER-8

    Template

    8.1 Introduction:

    Template is a framework which is used to create generic functions and classes. I a

    generic function or class, the type of the data that is operated upon is specified as a parameter.This allows us to use one function of class with several different types of data without having

    two explicitly recode a specific version for each different data type. This, templates allow us

    to create reusable code.

    8.2 Function template / Generic function:

    A generic function defines a general set of operations hat will be applied to various

    types of data. A generic function has the type of data that it will operate upon passed to it as

    parameter. Using this mechanism the same general procedure can be applied to a wide range

    of data. Once we create the generic function the compiler automatically generates the

    correct code for the type of data that is actually used when we execute the function. When wecreate a generic function we are creating a function that can automatically overload itself.

    A generic function is created using the keyword template. The general form of a

    template function is given below:

    template return_type function_name (parameter list)

    {

    . ; //body

    }

    OR

    template

    return type function name (parameter list)

    {

    . ; //body

    }

    Here, Ttype is a place holder name for a data type used by the function. The compiler ill

    automatically replace this place holder with an actual data type when it creates a specific

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    63/74

    version of the function. Instead of the keyword class we can also use the keyword type

    name to specify a generic type:

    e.g. the line

    template void show (X &a, X &b)

    tells the compiler two things:

    a. The template is being created.b. A generic definition is beginning.

    Here, X is a generic type that is used as place holder. After the template portion the

    function show is declared, using X as a data type of the values that will be swapped.

    SOME TERMS

    1. A generic function is also called a template function.2. When the compiler creates a specific version of this function it is set to have created a

    generated function.

    3. The act of generating function is referred as instantiating it.Notes

    1. The template portion of the generic function definition does not have to be on the sameline as the functions name.

    2. No other statement can occur between the template statement and start of the genericfunction definition i.e. the template specification must directly continue to the rest of the

    function definition.

    3. We can define more than one generic data type within the template statement, using a 9,)comma separated list.

    e.g. template

    8.3 Class template / Generic classes:

    When we define generic class, we create a class that defines all algorithms used by

    that class but the actual type of the data being manipulated will be specified as a parameter

    when object of that classes are created. Generic classes are useful when a class contains

    generalizable logic. By using generic class, we can create a class that will maintain stat, que,

    link list and so on for any type of data. The compiler will automatically generate the correct

    type of object based upon the type we specify when the object is created. The general form of

    a generic class declaration is:

    template class class_name

    Here, Ttype = place holder name that will be specified when a class is instantiated.

    Once we create a generic class we have to create specific instance of that class by using the

    following general form. Then the type is the type name of data that the class will be operated

    upon.

    Member functions of the generic class are themselves, automatically generic.

    C++ provides a library (standard template library or STL) i.e. build upon template classes. It

    provide generic version of the most commonly used algorithm and data structures.

    A template class can have more than one generic data type separated by comma (,) within the

    template specification.

    template < class type 1, class type 2> class myclass

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    64/74

    while instantiating in main( )

    myclass obj1 (10,70.000)

    myclass

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    65/74

    8.3.1 //sample program to function template

    #includeusing namespace std;

    template void swapargs (x &a, x &b)

    {

    x temp;

    temp =a;

    a=b;

    b=temp;

    }

    int main ( )

    {int i=10, j=20;

    float x=10.5, y=15.5;

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    66/74

    cin>>a;

    coutb;

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    67/74

    Exception Handling [4 hours]

    o Introductiono Basics of Exception Handlingo Exception Handling Mechanismo Throwing and Catching Exceptiono Re-throwing an Exception

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    68/74

    CHAPTER-9Exception Handling

    9.1 Introduction:C++ provides a built in error handling mechanism that is called exception handling.

    Using exception handling we can more easily manage and response synchronous runtime

    errors, which occur when a statement execute. Common examples of these errors are:

    Out-of-range-array-subscripts, arithmetic overflow, division by zero, invalid function

    parameters and unsuccessful memory allocation (due to lack of memory). In C++, exception

    handling is built upon 3 new keywords:a. tryb. catchc. throw

    9.2 Basics of Exception Handling:

    Program statement that we want monitor for exception are contained in try block. If

    an exception (i.e. an error) occurs within in the try block, it is thrown (using throw). The

    exception is caught, using catch and process. Any statement that throws an exception must

    have been executed form within a try block. Any exaction must be caught by a catch

    statement, which immediately follows the try statement that throws the exception.

    The general form of try and catch are shown as below:

    try

    {

    }

    catch (type 1 arg)

    {

    }

    catch (type 2 arg)

    {

    }

    catch (type n arg)

    {

    }

    The try block must contain the portion of our program that we want to monitor for

    errors when an exception is thrown; it is cut by its corresponding catch statement, which

    process the exception.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    69/74

    There can be more than one catch statement associated with try where the catch

    statement that is used is determined by the type of the exception. That is if the data type

    specified by a catch matches that of the exception, that catch statement is executed (all others

    are by passed).

    When an exception is caught, argument will receive its value.

    9.3 Exception Handling Mechanism:

    9.3.1 Sequence of events for exception handling :

    1.Code is executed normally outside a block.2.Control enters the try block.3.A statement in the try block causes an error in a member function.4.The member function throws an exception.5.Control transfers to the exception handler (i.e. catch block).6.Catch block takes corrective action to handle the exception.

    Any type of data can be caught (and thrown), including classes that will create.

    Exception is a value thrown.

    If we throw an exception for which there is no applicable statements, an abnormal program

    termination might occur, throwing an unhandled exception causes the standard library

    function terminate ( ) to invoke. By default, terminate function calls abort ( ) function to stop

    our program.

    Once an exception has been thrown control passes to the catch block and the try block is

    terminated. After catch block executes program control continues with the statements

    following catch.

    The type of exception must match the type specified in catch statement, if the type does notmatch the exception will not be caught and abnormal termination will occur.

    Although we can have more than one catch associated with a try. Each catch must catch

    different type of exception.

    An exception handler can catch all exception instead of just of certain type by using following

    form of catch.

    catch ( )

    {

    }

    We can restrict the type of exceptions that a function can throwback to its caller by using

    following form

    return_type function_name (argument list) throw (type list)

    {

    .

    }

    int myfunc (int i) throw (int i) throw (int a, float y,double d)

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    70/74

    Only these data types obtained in comm. Separated type list. Throwing any other type of

    exception will occur abnormal program termination by calling standard library function

    unexpected ( ) which causes the terminate function to be called.

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    71/74

    Following statement prevents X handler to throw an exception

    Void Xhandler (int test) throw ( )

    {

    try

    {

    .

    }

    catch (int b)

    {

    }

    9.4 Throwing and Catching Exception:9.4.1 Throwing an Exception:

    When an exception that is desired to be handled is detected. It is thrown using one of

    the following throw statements

    throw (exception)

    throw exception

    throw; //used for re-throwing in exception without using argument.

    9.4.2 Catching an Exception:

    Catch block include code for handling exception. When an exception whose type

    matches with the type of catch statement the exception is caught and the code in the catch is

    executed.

    catch (type arg)

    {

    //statements for managing exception

    }

    9.5 Re- Throwing an Exception:A handler may decide not to process an exception caught by it. In such cases we can

    re-throw an exception. The most likely reason for doing so is to allow multiple handler access

    to the exception.

    e.g. perhaps one exception handler manages one aspect of an exception and a second

    handler copes with another exception. An exception can only be re-thrown from within a

    catch block (or from any function call from within that block). When we re-throw an

    exception, it will not be re-caught by the same catch block (statement). It will propagate to an

    outer (next) catch statement (block).

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    72/74

    9.5.1 //sample program for exception handling

    #include

    using namespace std;

    int main ( )

    {

    cout

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    73/74

    9.5.2 //sample program to demonstrate exception

    #include

    using namespace std;const int MAX =3; //stack holds 3 intergers

    class stack

    {

    private:

    int st[MAX]; //array of integers

    int top; //index of top of stack

    public:

    class Full

    { }; //exception class of stack with empty body to connect a throw statement with a

    catch blockclass Empty

    {};

    stack ( ) //constructor

    {

    top = -1;

    }

    void push(int var)

    {

    if (top >=MAX -1) //if stack full

    throw Full ( ); //throw full exception

    st[++ top]=var; //put number on stack

    }

    int pop ( )

    {

    if (top

  • 7/21/2019 Lecture_Notes_COMP 116, Class Note

    74/74

    cout