home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!enterpoop.mit.edu!ira.uka.de!slsvaat!josef!kanze
- From: kanze@us-es.sel.de (James Kanze)
- Subject: Re: Question of scope
- In-Reply-To: chw@bellcore.com's message of Fri, 22 Jan 93 18:45:58 GMT
- Message-ID: <KANZE.93Jan28163859@slsvdnt.us-es.sel.de>
- Sender: news@us-es.sel.de
- Organization: SEL
- References: <1993Jan22.184558.21397@porthos.cc.bellcore.com>
- Date: 28 Jan 93 16:38:59
- Lines: 60
-
- In article <1993Jan22.184558.21397@porthos.cc.bellcore.com>
- chw@bellcore.com (Charlie Woloszynski,MRE 2J-278,8295228,,27143)
- writes:
-
- |> I have a class Base from which I derive several additional classes, as in:
-
- |> class Base
- |> {
- |> virtual Draw();
- |> }
-
- |> class Derived1 : public Base
- |> {
- |> virtual Draw();
- |> }
-
- |> I need to pass a pointer to an instance of one of these derived classes
- |> to a function (so I can make use of the derived functions) like:
-
- |> void foo(Base *p)
- |> {
- |> p->Draw();
- |> }
-
- |> Now I generally need to create the Derived classes only to pass them
- |> to foo. I don't want these instances to exist after the call to foo.
-
- |> Anyway, does the following call the destructor just after returning
- |> from the foo?
-
- |> foo(& Derived1());
-
- |> Does it have any ugly portability problems?
-
- Is this even legal? I do not believe that Derived1() is an lvalue,
- and so you should not be able to take its address. (There is a lot of
- discussion of this at present in the ANSI committee.)
-
- What you probably want to do is to define foo as follows:
-
- void
- foo( const Base& obj )
- {
- obj.draw() ;
- }
-
- Of course, "draw" would have to be declared "const". But since you
- are attempting to use it on temporary objects, this is probably what
- you want anyway.
-
- You could then call foo with:
- foo( Derived1() ) ;
- with supposedly no problems. This should work, as a temporary object
- used to initialize a reference has the same lifetime as the reference,
- which should keep it around until you return from the function.
- --
- James Kanze email: kanze@us-es.sel.de
- GABI Software, Sarl., 8 rue du Faisan, F-67000 Strasbourg, France
- Conseils en informatique industrielle --
- -- Beratung in industrieller Datenverarbeitung
-