TITLE: const, references, and temporaries RESPONSE: jamshid (Jamshid Afshar) [ ... ] While we're on the subject of warnings, some very definite code errors are indicated by the warnings in wbDesign/grwbpage.cc like: "grwbpage.cc", line 1595: warning: temporary used for non-const const specLine*& argument; no changes will be propagated to actual argument (anachronism) You may only initialize a non-const reference to a "real" object: int foo(); int& r1 = 5; // error int& r2 = foo(); // error const int& s1 = 5; // okay const int& s2 = foo(); // okay Don't get confused by a `const' and pointers: const specLine*& r1 = NULL; // error: r1 is a non-const reference const specLine* const& r2 = NULL; // okay: reference itself is const But, if you're using the latter, why use a reference? const specLine* s = NULL; PROBLEM: doug@foxtrot.ccmrc.ucsb.edu (Douglas Scott) typedef BaseClass * &BasePtrRef; // reference-to-pointer type void fun2(BasePtrRef bpr); main() { DerivedClass *dc = new DerivedClass; fun2(dc); // passing pointer-to-Derived as reference-to-pointer-to-Base } RESPONSE: jamshid (Jamshid Afshar) The above code is illegal, though some compilers might accept it for backward compatibility. A |DerivedClass*| does convert to a |BaseClass*|, but it is not a |BaseClass*|. You can only initialize a reference to some type T (in this case a |BaseClass*|) with an actual T object (an 'lvalue' in legalese). DerivedClass* d; BaseClass* bp = d; // okay BaseClass* & bpr = d; // error Allowing the last line above would lead to serious, undiagnosed type errors: bpr = new BaseClass; // woops! now d points to a BaseClass object d->some_d_thing(); // serious run-time error The relationship between |DerivedClass*| and |BaseClass*| is analogous to the relationship between int and long: int i; long l = i; // okay, an int converts to a long long& l = i; // error, an int is not a long One more thing: a *const* reference to T can be initialized with either a T *or* something which can convert to a T. In the latter case a temporary T will be created by the compiler. DerivedClass* d; typedef BaseClass* BaseClassPtr; const BaseClassPtr& bpr = d; // temporary BaseClass* created Older C++ rules stated that the same thing would be done for non-const references, which is why some compilers accept the original code. Complain to your compiler writer if you're not getting at least a stern warning. [ ... ]