Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.lang.c++ Subject: Re: Inheritance and references question Message-ID: <71032@microsoft.UUCP> Date: 4 Mar 91 20:02:13 GMT References: <1991Feb26.060459.6777@csun.edu| Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Organization: Microsoft Corp., Redmond WA Lines: 63 In article <1991Feb26.060459.6777@csun.edu| abcscnge@csunb.csun.edu (Scott Neugroschl) writes: | |Hi. I have a question about inheritance and references. | |I have the following classes: | | class StackEntry { | public: | StackEntry() { } | virtual ~StackEntry() { } | }; | | class Stack { | public: | // ... | Stack& operator>(StackEntry*&); // Stack pop operator | // .... | private: | // ... | }; | | 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? As far as I can tell from ARM, neither is right. Section 8.4.3 says that when initializing a reference, if the initializer is an exact match or of a type derived from an exact match as an accessible base, then the initialization is accepted, and no temporary is generated. Otherwise, if the initializer is a const, a temporary is generated. Otherwise "error." In which case, your example is in error, and dp should require an explicit (reference) cast. I don't like this definition, mind you. I'd like the pertinent section in 8.4.3 to say: If the initializer for a reference to type T is an lvalue of type T or of a type derived from T for which T is an accessible base or if T and the initializer are pointers or references to such, then 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. This change would allow references to pointer or references to accessible base types be initialized by pointers or references to derived types, as you desire, and as common sense would seem to indicate.