Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Constructors  in  the  Base  and  Derived  Classes

It   is   important   to   note   that  the   constructors   are   not   inherited  in  the  inheritance process,  unlike  other  methods  that  are  inherited.   This  fact  puts  the  burden  on  the programmer  to  provide  a  compulsorily  special  constructor  in  the  derived  class.

When   you   declare   an   object   of   a   derived   class,   the  compiler  executes  the constructor function  of  the  base  class  followed  by  the constructor  function  of  the derived class.

The   parameter   list   for   the  derived  class's   constructor   function   could   be  different  from that  of  the  base  class's  constructor  function.  Therefore,  the  constructor  function  for the derived  class  must  tell  the  compiler  what  values  to  use  as  arguments  to  the constructor function  for  the  base  class.

The  derived  class's  constructor  function  specifies  the  arguments  to  the  base  class's constructor  function.



           D ( int  a1,  int  a2,  float  b1,  float  b2,  int  d1 ) : A ( a1,  a2 ),  B ( b1,  b2 )
           {

                     d = d1 ;

           }



The   colon ( : )   operator   after   the  derived   constructor's   parameter   list   specifies  in  this case  that  an  argument  list  for  a  base  class's  constructor  follows.  The  argument  list  is  in parentheses  and  follows  the  name  of  the  base  class.

When  a  base  class  has  more   than   one   constructor  function,  the  compiler  decides  which one   to   call   based   on   the  types  of  the  arguments  in  the  base  constructor argument  list as specified  by  the  derived  class  constructor  function.

One  important  thing  to  note  here  is  that,  as  long  as  no  base  class  constructor  takes any arguments,   the  derived  class  need   not   have  a  constructor  function.  However,  if   any   base   class   contains   a   constructor   with   one   or   more   arguments,   then   it   is mandatory for  the  derived  class  to  have  a  constructor  and  pass  the  arguments  to  the  base  class constructors.

When  both  the  derived  and  base  classes  contain  constructors,  the  base  constructor  is executed  first  and  then  the  constructor  in  the  derived  class  is  executed.

In  case  of  multiple  inheritance,  the  base  classes  are  constructed  in  the  order   in  which they appear  in  the  declaration  of  the  derived  class.