Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Overriding  Base  Class  Functions  in  the  Derived  Class

When  a  base  and  a  derived  class  have  public  member  functions   with  the  same name and  parameter  list  types,  the  function  in  the  derived  class  overrides  that  in  the base class  when  the  function  is  called  as  a  member  of  the  derived  class  object.



Consider  the  following  code:



                                                          class  time
                                                          {
                                                                     protected :

                                                                                   int  hr ;
                                                                                   int  min ;
                                                                                   int  sec ;

                                                                     public :

                                                                                   void  settime( int  h,  int m,  int  s ) ;
                                                                                   void  show ( ) ;
                                                          } ;


                                                          class  clock  :  public time
                                                          {
                                                                       
                                                                                   char  str[ 5 ] ;     //  for  AM  PM

                                                                     public :

                                                                                   void  setAMPM( ) ;
                                                                                   void  show ( ) ;
                                                         } ;




Now  if  we  declare  an  object  t  of  class  clock  and  then  invoke  t.show ( ),  which method should  be  executed?  The  one  defined  in  base  class  or  in  the  derived  class?

In  this  case  the  function  in  the  derived  class  will  be  executed.  It  will  override  the function  in  the  base  class.