Page 220 - DCAP404 _Object Oriented Programming
P. 220

Unit 10: Virtual Functions and Polymorphism




          virtual int sum (int xx, int IT); //base class                                        Notes
          virtual float sum (int xx, int IT); //derived class
          Both the above functions can be written with int data types in the base class as well as in the
          derived class as
          virtual int sum (int xx, int yy); //base class
          virtual int sum (int xx, int yy); //derived class
          Only a member function of a class can be declared as virtual. A non member function (nonmethod)
          of a class cannot be declared virtual.
          virtual  void  display  ()  //error,  nonmember  function
          {
          Function  body

          }
          10.1.1 Late Binding

          Late binding means selecting functions during the  execution. Though late binding  requires
          some overhead  it provides increased power and flexibility. The late binding is implemented
          through virtual functions as a result we have to declare an object of a class either as a pointer to
          a class or a reference to a class.



             Did u know?  What is static binding?
             By default, C++ matches a function call with the correct function definition at compile
             time. This is called static binding.
          For example the following shows how a late binding or run time binding can be carried out with
          the help of a virtual function.
          class  base  {
          private  :
          int  x;
          float  y;
          public:
          virtual  void  display  (  );

          int  sum  (  );
          };
          class  derivedD  :  public  baseA
          {
          private:
          int  x;
          float  y;

          public:




                                           LOVELY PROFESSIONAL UNIVERSITY                                   213
   215   216   217   218   219   220   221   222   223   224   225