Inheritance based type conversion and private inheritance
Hello everybody!
I have just been playing around a little with inheritance based type
conversion and I am using Microsoft Visual C++ 2005 Express Edition to
compile the following code:
template <typename T>
class SmartPtr
{
T* m_ptr;
public:
SmartPtr( T* ptr = 0 )
: m_ptr( ptr ) {}
~SmartPtr()
{ delete m_ptr; }
template <typename U>
operator SmartPtr<U>()
{
// An accessible conversion from type
// pointer-to-T to type pointer-to-U
// must exist for this to compile.
return SmartPtr<U>( m_ptr );
}
};
class Base
{
// Required for polymorphic deletion,
// though this is just a side issue.
virtual ~Base() {}
};
// Note private inheritance.
class Derived : Base {};
int main()
{
// Error: A conversion from Derived* to
// Base* exists, but is not accessible.
SmartPtr<Base> ptr_err ( new Derived );
// Compiles fine.
SmartPtr<Derived> ptr_d ( new Derived );
// Compiles fine.
SmartPtr<Base> ptr_b = ptr_d;
return 0;
}
When SmartPtr<Derived>::operator SmartPtr<Base>() is instantiated, an upcast
from Derived* to Base* is performed. This compiles fine, although the
conversion from Derived* to Base* should not be accessible within the
instantiation of that member function template.
Note that SmartPtr<T>::operator SmartPtr<U>() is not a friend of Derived,
which inherits privately from Base. The first line of code in main() does
the same thing as the conversion operator, but my compiler rejects it.
Is this a compliance issue with my compiler? And if not, why does the upcast
work within the conversion operator, but not outside of it?
--
Matthias Hofmann
Anvil-Soft, CEO
http://www.anvil-soft.com - The Creators of Toilet Tycoon
http://www.anvil-soft.de - Die Macher des Klomanagers
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]