Article View: comp.std.c++
Article #2030Inheritance and references to pointers
From: Jean-Rene Bouvier
Date: Mon, 25 Sep 1995 07:25
Date: Mon, 25 Sep 1995 07:25
52 lines
2668 bytes
2668 bytes
In a number of libraries, the following trick is used to denote the acquisition
of a pointer and to make it inaccessible to callers:
void GrabPointer(Object*& object)
{
Object* obj = object;
object = 0;
// Now, work with obj ...
}
Callers who pass pointers to GrabPointer() will not be able - upon return from
the function - to access the object the pointer used to refer to.
This nice trick is defeated in presence of inheritance; i.e. if instead of
passing an Object*, the caller wants to pass a DerivedObject*, a compilation
error should be issued (at least, this is my understanding, and this is also
what Borland 4.5 and HP 3.5 compilers do).
This is very unfortunate, and it also makes the use of references to pointers
counter-intuitive: after all, if a reference hadn't been used, passing a
DerivedObject* would have been perfectly legal.
My questions thus are:
1. is my understanding correct (i.e. that a DerviedObject*& cannot be passed
in lieu of an Object*&) ?
2. what is the reason for this restriction, or rather, is there any reason to
keep this restriction (apart from the fact that a DerviedObject*& bears no
inheritance relationship to an Object*&) ?
3. More generally, why isn't there a generalization of the fact that:
DerivedObject can be passed to a function expecting an Object (slicing),
DerivedObject* can be passed to a function expecting an Object*,
DerivedObject& can be passed to a function expecting an Object&,
so that further indirections/references would be allowed:
DerivedObject** could be passed to a function expecting an Object**,
DerivedObject*& could be passed to a function expecting an Object*&,
DerivedObject*** could be passed to a function expecting an Object***,
... ?
Email replies are welcome (to: jr@grenoble.hp.com)
Thanks,
- jr
[jean-rene bouvier]
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID:
<445k3k$18p@isoit109.bbn.hp.com>Path:
arc1-ca.pugleaf.net!in1.uu.net!bounce-backShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!in1.uu.net!bounce-back Date: 25 Sep 95 07:25:20 GMT Approved: fjh@cs.mu.oz.au From: Jean-Rene Bouvier <jr@isoit109.bbn.hp.com> Newsgroups: comp.std.c++ Subject: Inheritance and references to pointers X-Original-Date: 25 Sep 1995 07:01:08 GMT Organization: hp Message-ID: <445k3k$18p@isoit109.bbn.hp.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Mailer: Mozilla 1.1N (X11; I; HP-UX A.09.01 9000/735) X-Url: news:comp.std.c++