class CBase
{
public:
CBase() {}
virtual ~CBase() {}
};
class CDerived : public CBase
{
public:
CDerived() {}
virtual ~CDerived() {}
};
void Foo(SmartPointer<CBase> ptr)
{
}
SmartPointer<CDerived> pDerived = new CDerived;
Foo(pDerived);
Quote: error C2664: 'Foo' : cannot convert parameter 1 from 'SmartPointer<T>' to 'SmartPointer<T>' with [T=CDerived] and [T=CBase] No user-defined-conversion operator available that can perform this conversion, or the operator cannot be calledHowever, changing to call to Foo() to this, works: Foo(SmartPointer<CBase>(pDerived)); So why can't it do an implicit conversion itself? Here's the entire source of my smart pointer class:
//==========================================================================
// SmartPointer.h - Smart pointer classes
//==========================================================================
#ifndef __SMARTPOINTER_H__
#define __SMARTPOINTER_H__
#include "Assert.h"
//==========================================================================
// Smart pointer base class. All classes using smart pointers must
// derive from this class
//==========================================================================
class CRefCounted
{
public:
CRefCounted() : m_nRefCount(0) {}
virtual ~CRefCounted() {Assert(m_nRefCount == 0);}
// Increment the reference count for this object
void addRef() {++m_nRefCount;}
// Decrement the reference count for this object
void decRef()
{
if(--m_nRefCount == 0)
delete this;
else
Assert(m_nRefCount > 0);
}
private:
int m_nRefCount;
};
//==========================================================================
// Smart pointer template class
//==========================================================================
template<class T> class SmartPointer
{
public:
SmartPointer() : m_pObj(0) {}
SmartPointer(const SmartPointer& rhs) : m_pObj(rhs.m_pObj)
{if(m_pObj) m_pObj->addRef();}
SmartPointer(T* rhs) : m_pObj(rhs)
{if(m_pObj) m_pObj->addRef();}
~SmartPointer() {if(m_pObj) m_pObj->decRef();}
SmartPointer& operator=(T* rhs)
{
if(m_pObj) m_pObj->decRef();
m_pObj = rhs;
if(m_pObj) m_pObj->addRef();
return *this;
}
SmartPointer& operator=(const SmartPointer& rhs)
{
if(m_pObj) m_pObj->decRef();
m_pObj = rhs.m_pObj;
if(m_pObj) m_pObj->addRef();
return *this;
}
T& operator*() const {return *m_pObj;}
T* operator->() const {return m_pObj;}
operator T*() const {return m_pObj;}
private:
T* m_pObj;
};
#endif /* __SMARTPOINTER_H__ */