TITLE: Temporaries and const member functions PROBLEM: Dimitri Tischenko (dimitri@dutiws.tudelft.nl) class A { public: A() { i=0; } virtual A& foc() const { return *this; } // 18:error : declaration of object of abstract class A // 18:warning: const initializer: temporary used to initialize reference // 18:warning: reference to temporary returned (return value is not lvalue private: int i; }; RESPONSE: Robert C. Martin (rmartin@rational.com) The ARM section 9.3.1 says: "The type of 'this' in a member function of class X is X *const unless the member function is declared 'const' or 'volatile'; in those cases, the type of 'this' is const X* const and volatile X* const, respectively." In your case, within the function 'foc' the type of 'this' is const A* const. But foc returns A& which is not const. Thus the compiler has to create a temporary volatile version of A. However A is abstract so the compiler can't instantiate it. You can get rid of the compiler errors by changing the declaration of foc to 'virtual const A& foc() const {return *this;}' If you look closely you will realized that the original form of foc would have been a nasty bug, even if A had not been abstract. foc declares itself to be const, promising that it will not change its object. 'return *this;' forces the compiler to create a temporary since it can't pass a const object (this) out through a volatile interface (the return value). So the function returns a reference to a temporary. But the temporary was created *inside* foc and will be destroyed when foc exits. Thus foc returns a reference to an object which no longer exists. [ Ouch! Be sure you understand this. It would be time-consuming to find this one. -adc ]