Path: utzoo!mnetor!tmsoft!torsqnt!hybrid!scifi!bywater!uunet!world!wmm From: wmm@world.std.com (William M Miller) Newsgroups: comp.lang.c++ Subject: Re: Inheritance and references question Message-ID: <1991Feb26.143955.8494@world.std.com> Date: 26 Feb 91 14:39:55 GMT References: <1991Feb26.060459.6777@csun.edu> Organization: The World Public Access UNIX, Brookline, MA Lines: 47 abcscnge@csunb.csun.edu (Scott Neugroschl) writes: > I have the following classes: > > class Stack { > Stack& operator>(StackEntry*&); // Stack pop operator > }; > > class Disk : public StackEntry { > }; > Stack s; > Disk *dp; > s > dp; // pop s into dp <<== PROBLEM HERE > > Now the question. > Turbo C++ generates a temporary variable (implicit type cast) so that > dp never gets set. G++, on the other hand allows the construct, and > the code does what I expect. Since Disk is a subclass of StackEntry, > and a Disk* can be assigned to a StackEntry*, I think G++ is right. > Is it? If not, why? Turbo C++ has it right, G++ is wrong. Here's what E&S has to say (section 8.4.3, page 154): "If the initializer for a reference to type T is an lvalue of type T or of a type derived (section 10) from T for which T is an accessible base (section 4.6), the reference will refer to the initializer; otherwise, if and only if the reference is to a const an object of type T will be created and initialized with the initializer." The key fact here is that, although Disk is derived from StackEntry, Disk* is NOT derived from StackEntry*; they are different types. (The restriction to const references, BTW, is a change from the 2.0 definition on which Turbo C++ is based, so it's not a bug that the compiler creates a temporary instead of issuing an error; under a fully 2.1-compliant compiler, though, the "s > dp" would be an error.) As another way of looking at this, think of the analogy with int and long. You can convert an int to a long, just as you can convert a Disk* to a StackEntry*, but clearly an int& is not compatible with a long&. While it's true that there are probably no representation differences between a Disk* and StackEntry*, the type implications on which the treatment of references is based are exactly the same as for int and long. > Please respond via Email, as I don't get on this system too often. I've done so, but I thought this question was of sufficient interest to warrant posting, as well. -- William M. Miller, Glockenspiel, Ltd. wmm@world.std.com