Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Dynamic  Memory  Allocation  for  a  Single  Instance  of  a  User-defined  Type

Memory  for  a  single  instance  of  a  user-defined  class  can  be  obtained  from  the heap in  the  same  fashion  as  that  of  a  built-in  type.  That  is,  you  write  the  keyword   new   followed  by  the  class  type.


For  example,

Item * ptr  =  new  Item ;

allocate  one  object  of  type  Item.


The  pointer  returned  by


new  Item ;


is  of  correct  type ( pointer  to  Item ) without  the  need  for  explicit  casting.


 In  this  example,  the  first  step  is  to  allocate  space  for  the  instance  of  Item  and  the  second  step  is  to  call  the  appropriate  constructor  of  the  class  Item.


Item *  ptr  =  Item ( 17 ) ;


The  parentheses  following  the  class  name,  if  present,  supply  arguments  to  the  class constructor.  If  the  parentheses  are  not  present,  as  in


Item * ptr  =  new  Item ;


then  the  class  must  either  define  a  constructor  that  does  not  require  arguments  or define  no  constructors  at  all.




Dynamic  Memory  Allocation  for   an  array  of  Objects

Programmer  may  also  ask  for  more  than  one  instance,  that  is,  an  array  of  objects  of a  particular  type. The  array  is  allocated  from  the  free  store  by  following  the  type specifier  with  a  bracket-enclosed  dimension.  The  dimension  can  be  any  expression.


For  example,

Item *  =  new  Item [ 5 ] ;


allocate  space  for  5  objects  of  type  Item  and  call  default  constructor  for  all  objects.

In  particular,  if  a  class  lacks  a  default  constructor,  there  are  restrictions  on  how  you can  use  that  class.  It  is  not  usually  possible  to  create  array  of  objects.

If  a  class  lacks  a  default  constructor then,


  Item *  =  new  Item [ 5 ] ;


results  in  an  error,  no  way  to  call  Item  constructors.