Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Pointers  to  Base  and  Derived  classes

We  can  use  pointers  not  only  to  the  base  objects  but  also  to  the  objects  of  derived classes.  Pointers  to  objects  of  a  base  class  are  type-compatible  with  pointers  to objects of  a  derived  class.  Therefore,  a  single  pointer  variable  can  be  made to  point  to objects belonging  to  different  classes.


Consider  the  following  declarations:




                                              class  Derived : public  Base
                                              {
                                                          // . . .

                                                          // . .
                                               } ;


                                               Base  b ;

                                               Base  *ptr ;

                                               
Derived  d ;

                                               ptr = & b ;

                                               ptr = & d ;



This  is  perfectly  valid  with  C++  because  d  is  an  object  derived  from  the  class   Base.
However,  there  is  a  problem  in  using  ptr  to  access  the  public  members  of  the  derived class.  Using  ptr,  we  can  access  only  those  members  inherited  from  base  and  not  the members  that  originally  belong  to  derived  class.  If  a  derived  class  member  overrides  a base  class  member,  the  pointer  ignores  the  override.