home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / cplus / 20026 < prev    next >
Encoding:
Text File  |  1993-01-28  |  2.2 KB  |  73 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!enterpoop.mit.edu!ira.uka.de!slsvaat!josef!kanze
  3. From: kanze@us-es.sel.de (James Kanze)
  4. Subject: Re: Question of scope
  5. In-Reply-To: chw@bellcore.com's message of Fri, 22 Jan 93 18:45:58 GMT
  6. Message-ID: <KANZE.93Jan28163859@slsvdnt.us-es.sel.de>
  7. Sender: news@us-es.sel.de
  8. Organization: SEL
  9. References: <1993Jan22.184558.21397@porthos.cc.bellcore.com>
  10. Date: 28 Jan 93 16:38:59
  11. Lines: 60
  12.  
  13. In article <1993Jan22.184558.21397@porthos.cc.bellcore.com>
  14. chw@bellcore.com (Charlie Woloszynski,MRE 2J-278,8295228,,27143)
  15. writes:
  16.  
  17. |> I have a class Base from which I derive several additional classes, as in:
  18.  
  19. |> class Base 
  20. |> { 
  21. |>   virtual Draw(); 
  22. |> } 
  23.  
  24. |> class Derived1 : public Base 
  25. |> { 
  26. |>   virtual Draw(); 
  27. |> } 
  28.  
  29. |> I need to pass a pointer to an instance of one of these derived classes 
  30. |> to a function (so I can make use of the derived functions) like:
  31.  
  32. |> void foo(Base *p) 
  33. |> { 
  34. |>   p->Draw(); 
  35. |> } 
  36.  
  37. |> Now I generally need to create the Derived classes only to pass them
  38. |> to foo.  I don't want these instances to exist after the call to foo.
  39.  
  40. |> Anyway, does the following call the destructor just after returning
  41. |> from the foo?
  42.  
  43. |>    foo(& Derived1());
  44.  
  45. |> Does it have any ugly portability problems? 
  46.  
  47. Is this even legal?  I do not believe that Derived1() is an lvalue,
  48. and so you should not be able to take its address.  (There is a lot of
  49. discussion of this at present in the ANSI committee.)
  50.  
  51. What you probably want to do is to define foo as follows:
  52.  
  53.     void
  54.     foo( const Base& obj )
  55.     {
  56.         obj.draw() ;
  57.     }
  58.  
  59. Of course, "draw" would have to be declared "const".  But since you
  60. are attempting to use it on temporary objects, this is probably what
  61. you want anyway.
  62.  
  63. You could then call foo with:
  64.     foo( Derived1() ) ; 
  65. with supposedly no problems.  This should work, as a temporary object
  66. used to initialize a reference has the same lifetime as the reference,
  67. which should keep it around until you return from the function.
  68. --
  69. James Kanze                             email: kanze@us-es.sel.de
  70. GABI Software, Sarl., 8 rue du Faisan, F-67000 Strasbourg, France
  71. Conseils en informatique industrielle --
  72.                    -- Beratung in industrieller Datenverarbeitung
  73.