I came across the following piece of code in the book on data structures by Mark Allen Weiss.
template <class Object>
class Cref
{
public:
Cref ( ) : obj ( NULL ) { }
explicit Cref( const Object & x ) : obj ( &x ) {
const Object & get( ) const
{
if ( isNull( ) )
throw NullPointerException( ) ;
else
return *obj;
}
bool isNull( ) const
( return obj == NULL; }
private:
const Object *obj;
};
So the point here is to assign null/initialize a constant reference. But I am not sure I understand the following:
1. We initialize a constant reference with another constant reference x. But why is it again done as obj(&x) ? the & in const Object & x is different from the &x in obj(&x) ? I see this but not very clear why it should be so. Pls explain.
2. The get method() – We try to return a const reference of the private member obj of this class. It is already a const reference. Why return *obj and not just obj ?
3. Why explicit keyword ? What might happen if an implicit type conversion takes place ? Can someone provide a scenario for this ?
Thanks
The member
objis of typeObject*, but the constructor takes a reference. Therefore to get a pointer, the address-of operator,&, has to be applied. And the member is a pointer because it can be NULL (set in the default constructor), and references never can be NULL.The private member is not a const reference, but a poinetr to const. It is dereferenced to get a reference.
In this specific case, I cannot see any negative effect of a potential implicit conversion either.