Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Temporary  Objects

It  is  always  possible  to  create  a  temporary  instance  of  a  class  by  writing  the  class name  followed  by  parentheses,  within  which  the  constructor  arguments,   if   any,   are specified.  If  there  are  no  arguments  to  be  used  in  the  constructor  of  the  instance, the  parentheses  must  still  be  written.  The  constructor  function  will  then  be  called when  the  temporary  instance  is  created.



For  Example,

                                                           Distance  create ( int  feet,  float  inches )
                                                           {
                                                                   return  Distance ( feet,  inches ) ;
                                                           }



In  some  circumstances,  it  may  be  essential  for  the  compiler  to  create  a  temporary object.  For  example,  when  a  function  is  called  that  takes  a  class  object  passes into or  out  of  it  by  value.  When  a  compiler  generates  a  temporary  object  of  a  class that  has  a  constructor,  it  must  invoke  a  suitable  constructor  for  the  temporary object. Similarly,  a  destructor  must  be  applied  to  a  temporary  object  of  a  class  that has  a destructor.



For  Example,

                                                           void  Func ( Distance  v )
                                                           {
                                                                       // . . .
                                                                       // . .  
                                                           }