Notes on specific C++ topics

Embed Size (px)

Citation preview

  • 8/18/2019 Notes on specific C++ topics

    1/17

    1

    Function Overriding

    • Functions with same name and same parameters and same return type

    • Defined in base class and derived classes

    • When derived class object calls the function, it calls overridden function in the derived class•  When base class object calls the function, it calls the base class copy of the function

    Function overriding Example

    Pointer to a derived object- Problem without Virtual Keyword 

    class Base

    { public:

     void show()

     {

      cout

  • 8/18/2019 Notes on specific C++ topics

    2/17

    2

     public:

     void show()

     {

      cout

  • 8/18/2019 Notes on specific C++ topics

    3/17

    3

     When derived class object is assi$ned to base class pointer, base class pointer will access the

    overridden derived class function durin$ run time .&his is know as run time polymorphism +

    dynamic bindin$

     Run time polymorphism Example

    bstract !lass

    bstract (lass is a class which contains atleast one )ure #irtual function in it. bstract classes

    are used to provide an "nterface for its sub classes. (lasses inheritin$ an bstract (lass must

     provide definition to the pure virtual function, otherwise they will also become abstract class.

    Note: - Classes that can be used to instantiate objects are called concrete classes.

  • 8/18/2019 Notes on specific C++ topics

    4/17

    4

    Characteristics of Abstract Class

    . bstract class cannot be instantiated, but pointers and references of bstract class typecan be created.

    -. bstract class can have normal functions and variables alon$ with a pure virtual function.

    . bstract classes are mainly used for /pcastin$, so that its derived classes can use its

    interface.

    0. (lasses inheritin$ an bstract (lass must implement all pure virtual functions, or elsethey will become bstract too.

     Pure Virtual Functions

    )ure virtual Functions are the virtual member functions of base class without definition andforces derived class to $ive definition for it.

    &hey start with virtual keyword and ends with 1 2. 3ere is the synta4 for a pure virtual function,

    5.$. class 6hape7 virtual void area89 1 2:

    ;:

    "t is initiali indicates that code for the function is null pointer.

    "f derived class fails to provide definition for the function, then it becomes an abstract class and

    instance of it can not be created then.

     Abstract Class Example 1

    class Base ++bstract base class

    7

     public? virtual void show"# $ %&  ++)ure #irtual Function

    ;:

    class Derived?public Base

    7 public?

     void show89 7 cout @@ A"mplementation of #irtual Function in Derived classA: ;

    ;:

    int main89

    7

  • 8/18/2019 Notes on specific C++ topics

    5/17

    5

     Base obj: ++(ompile &ime 5rror 

     Base b:

     Derived d: b 1 Cd:

     bEshow89:

    ;utput ? "mplementation of #irtual Function in Derived class

    "n the above e4ample Base class is abstract, with pure virtual show"# function, hence we cannot

    create object of base class.

    Why cant !e create "b#ect of Abstract Class $

    When we create a pure virtual function in bstract class, we reserve a slot for a function, but it

    doesn't put any address in that slot. 3ence the function will be incomplete.

    s the function for bstract class is incomplete, hence the compiler will not let the creation of 

    object for such class and will display an errror messa$e whenever you try to do so.

     Abstract Class Example%&

    Consider the following example where parent class provides an interface to the base

    class to implement a function called getArea():

    &include

  • 8/18/2019 Notes on specific C++ topics

    6/17

    6

    class 0ectan'le: public hape

    {

    public:

      int 'et-rea()

      {

    return (width * hei'ht);

    }

    ;:

    class &rian$le? public 6hape7

     public?

      int $etrea89

      7return 8width hei$ht9+-:

    ;

    ;: 

    int main8void9

    7  Gectan$le Gect:

      &rian$le &ri: 

    Gect.setWidth8H9:

      Gect.set3ei$ht8I9:

      ++ )rint the area of the object.  cout @@ A&otal Gectan$le area? A @@ Gect.$etrea89 @@ endl:

      &ri.setWidth8H9:

      &ri.set3ei$ht8I9:

      ++ )rint the area of the object.  cout @@ A&otal &rian$le area? A @@ &ri.$etrea89 @@ endl:

    return 2:

    ;

    When the above code is compiled and e4ecuted, it produces the followin$ result?

    &otal Gectan$le area? H

    &otal &rian$le area? I

     Pure Virtual definitions

    • )ure #irtual functions can be $iven a small definition in the bstract class, which you

    want all the derived classes to have. 6till you cannot create object of bstract class.

    • lso, the )ure #irtual function must be defined outside the class definition. "f you will

    define it inside the class definition, complier will $ive an error. "nline pure virtualdefinition is "lle$al.

  • 8/18/2019 Notes on specific C++ topics

    7/17

    7

    class Base ++bstract base class

    7

     public? virtual void show"# $ %&  ++)ure #irtual Function

    ;:

    void Base ?? show89 ++)ure #irtual definition

    7

     cout @@ A)ure #irtual definitionJnA:;

    class Derived?public Base

    7 public?

     void show89

     7 cout @@ A"mplementation of #irtual Function in Derived classA: ;

    ;:

    int main897

     Base b:

     Derived d: b 1 Cd:

     bEshow89:

    ;

    Output :

    )ure #irtual definition

    "mplementation of #irtual Function in Derived class

    pplication designing 'trategy:

    n objectoriented system mi$ht use an abstract base class to provide a common and

    standardi

  • 8/18/2019 Notes on specific C++ topics

    8/17

    (O)*+,-V

    Virtual )estructors

    Destructors in the Base class can be #irtual. Whenever /pcastin$ is done, Destructors of the

    Base class must be made virtual for proper destrucstion of the object when the pro$ram e4its.

    .O/, : (onstructors are never #irtual, only Destructors can be #irtual.

    'pcasting !ithout Virtual (estructor 

    Kets first see what happens when we do not have a virtual Base class destructor.

    class Base

    7

     public?

     LBase89 7cout @@ ABase DestructorJtA: ;;:

    class Derived?public Base7

     public?

     LDerived89 7 cout@@ ADerived DestructorA: ;;:

    int main89

    7 Base b 1 new Derived: ++/pcastin$

     delete b:

     return 2:;

    utput ? Base Destructor 

    "n the above e4ample, delete b will only call the Base class destructor, which is undesirable

     because, then the object of Derived class remains undestructed, because its destructor is never

    called. Which results in memory leak.

    'pcasting !ith Virtual (estructor 

     *ow lets see. what happens when we have #irtual destructor in the base class.

    class Base

    7

  • 8/18/2019 Notes on specific C++ topics

    9/17

    !

     public?

     virtual LBase89 7cout @@ ABase DestructorJtA: ;

    ;:

    class Derived?public Base

    7 public?

     LDerived89 7 cout@@ ADerived DestructorA: ;

    ;:

    int main89

    7

     Base b 1 new Derived: ++/pcastin$ delete b:

     return 2:

    ;

    Output :Derived Destructor 

    Base Destructor When we have #irtual destructor inside the base class, then first Derived class's destructor is

    called and then Base class's destructor is called, which is the desired behaviour 

     Pure Virtual (estructors

    • )ure #irtual Destructors are le$al in (%%. lso, pure virtual Destructors must be defined,

    which is a$ainst the pure virtual behaviour.

    • &he only difference between #irtual and )ure #irtual Destructor is, that pure virtualdestructor will make its Base class bstract, hence you cannot create object of that class.

    • &here is no reuirement of implementin$ pure virtual destructors in the derived classes.

    class Base

    7 public?

     virtual LBase89 1 2: ++)ure #irtual Destructor 

    ;:

    0ase::10ase"# 7 cout @@ ABase DestructorA: ; ++Definition of )ure #irtual Destructor 

    class Derived?public Base7

     public?

     LDerived89 7 cout@@ ADerived DestructorA: ;;:

  • 8/18/2019 Notes on specific C++ topics

    10/17

    1"

    2hat is a virtual base class3

    n ambi$uity can arise when several paths e4ist to a class from the same base class. &his means

    that a child class could have duplicate sets of members inherited from a sin$le base class.

    (%% solves this issue by introducin$ a virtual base class. When a class is made virtual,

    necessary care is taken so that the duplication is avoided re$ardless of the number of paths that

    e4ist to the child class.

    2hat is Virtual base class3 ,4plain its uses5

    When two or more objects are derived from a common base class, we can prevent multiple

    copies of the base class bein$ present in an object derived from those objects by declarin$ the

     base class as virtual when it is bein$ inherited. 6uch a base class is known as virtual base class.

    &his can be achieved by precedin$ the base class! name with the word virtual.

    (onsider the followin$ e4ample

    class

    7 public?

    int i:

    ;:

    class B ? virtual public

    7

     public?

    int j:

    ;:

    class (? virtual public

    7

     public?

    int k:

    ;:

    class D? public B, public (

    7

     public?int sum:

    ;:

    int main89

    7

    D ob:

  • 8/18/2019 Notes on specific C++ topics

    11/17

    11

      ob.i 1 2: ++unambi$uous since only one copy of i is inherited.

    ob.j 1 -2:

    ob.k 1 2:

    ob.sum 1 ob.i % ob.j % ob.k:

    cout @@ =#alue of i is ? >@@ ob.i@@>Jn>:

    cout @@ =#alue of j is ? >@@ ob.j@@>Jn>: cout @@ =#alue of k is ?>@@ ob.k@@>Jn>:

    cout @@ =6um is ? >@@ ob.sum @@>Jn>:

    return 2:

    ;

    /emplates

  • 8/18/2019 Notes on specific C++ topics

    12/17

    12

    N &ypeindependent patterns that can work with multiple data types.

     O Peneric pro$rammin$

     O (ode reusable

    N Function &emplates

     O &hese define lo$ic behind the al$orithms that work for multiple data types.

    N (lass &emplates

     O &hese define $eneric class patterns into which specific data types can be plu$$ed

    in to produce new classes.

    Function and function templates

    (%% routines work on specific types. We often need to write different routines to perform the

    same operation on different data types.

    int ma4imum8int a, int b, int c9

     7

    int ma4 1 a:

    if 8b E ma49 ma4 1 b:

    if 8c E ma49 ma4 1 c:

    return ma4:

    ;

    float ma4imum8float a, float b, float c9

     7

    float ma4 1 a:

    if 8b E ma49 ma4 1 b:

    if 8c E ma49 ma4 1 c:

    return ma4:

    ;

  • 8/18/2019 Notes on specific C++ topics

    13/17

    13

    double ma4imum8double a, double b, double c9

     7

    double ma4 1 a:

    if 8b E ma49 ma4 1 b:

    if 8c E ma49 ma4 1 c:

    return ma4:

    ;

    &he lo$ic is e4actly the same, but the data type is different.

    -Function templates allow the logic to be written once and used for all data types –  generic

     function)

    Function *emplates

    N Peneric function to find a ma4imum value

    ,4ample 65

    &emplate @class &E

    & ma4imum8& a, & b, & c9

     7

    & ma4 1 a:

    if 8b E ma49 ma4 1 b:

    if 8c E ma49 ma4 1 c:

    return ma4:

    ;

    N &emplate function itself is incomplete because the compiler will need to know the actualtype to $enerate code. 6o template pro$ram are often placed in .h or .hpp files to be

    included in pro$ram that uses the function.

    N (%% compiler will then $enerate the real function based on the use of the function

    template.

    N Peneric function to find a ma4imum value

  • 8/18/2019 Notes on specific C++ topics

    14/17

    14

    Function /emplates *sage

    N fter a function template is included 8or defined9, the function can be used by passin$

     parameters of real types.

    &emplate @class &E

    & ma4imum8& a, & b, & c9

    Q

    int i, i-, i:

    Q

    int m 1 ma4imum8i, i-, i9:

    N ma4imum8i, i-, i9 will invoke the template function with &11int. &he function returns a

    value of int type.

    N 5ach call to ma4imum89 on a different data type forces the compiler to $enerate a

    different function usin$ the template. 6ee the ma4imum e4ample.

     O ne copy of code for many types.

    int i, i-, i:

      ++ invoke int version of ma4imum

      cout @@ A&he ma4imum inte$er value is? A

      @@ ma4imum8 i, i-, i 9:

    ++ demonstrate ma4imum with double values

      double d, d-, d:

      ++ invoke double version of ma4imum

      cout @@ A&he ma4imum double value is? A

      @@ ma4imum8 d, d-, d 9:

    ,4ample 7

  • 8/18/2019 Notes on specific C++ topics

    15/17

    15

    template@ class & E

    void printrray8 const & array, const int count 9

    7

    for 8 int i 1 2: i @ count: i%% 9

    cout @@ arrayR i S @@ A A: cout @@ endl:

    ;

    'sage

    template@ class & E

    void printrray8 const & array, const int count 9:

    char ccR22S:

    int iiR22S:

    double ddR22S:

    myclass 44R22S: @ user defined type can also be used.

    QQ

     printrray8cc, 229:

     printrray8ii, 229:

     printrray8dd, 229:

     printrray844, 229:

    ,4ample 8

    + (%% pro$ram to swap data entered by user. +

    Tinclude @iostreamE

    usin$ namespace std:template @typename &E

    void 6wap8& Cn, & Cn-9

    7& temp:

    temp 1 n:

    n 1 n-:

  • 8/18/2019 Notes on specific C++ topics

    16/17

    16

    n- 1 temp:

    ;

    int main89

    7

    int i1, i-1-:float f1., f-1-.-:

    char c1'a', c-1'b':

    cout@@ABefore passin$ data to function template.JnA:cout@@Ai 1 A@@i@@AJni-1A@@i-:

    cout@@AJnf 1 A@@f@@AJnf-1A@@f-:

    cout@@AJnc 1 A@@c@@AJnc-1A@@c-:

    6wap8i, i-9:

    6wap8f, f-9:

    6wap8c, c-9:

      cout@@AJnJnfter passin$ data to function template.JnA:

    cout@@Ai 1 A@@i@@AJni-1A@@i-:cout@@AJnf 1 A@@f@@AJnf-1A@@f-:

    cout@@AJnc 1 A@@c@@AJnc-1A@@c-:

    return 2:;

    Output

    Before passin$ data to function template.i 1

    i- 1 -f 1 .f- 1 -.-

    c 1 a

    c- 1 b

    fter passin$ data to function template.

    i 1 -i- 1

    f 1 -.-

    f- 1 .

    c 1 bc- 1 a

    'se of template function

    N (an any user defined type be used with a template functionU

     O *ot always, only the ones that support all operations used in the function.

  • 8/18/2019 Notes on specific C++ topics

    17/17

    17

     O 5.$. if myclass does not have overloaded @@ operator, the printarray template

    function will not work.