Topic: smart pointers and casting to base class
Author: jvsb@sebb.bel.alcatel.be (Johan Vanslembrouck)
Date: 28 Oct 1994 11:37:26 GMT Raw View
/*
I'm sure this question has come up before, but I can't find it back in my
archive. It has to do with making smart pointers behave like normal pointers.
In particular, you can assign a normal pointer to a derived class object to
a pointer to a base class object. This is not possible when
a so-called smart pointer class (a class embedding a pointer
to the actual object with some extra behaviour if required) is used.
In the program below, I've used a template class for the smart pointer class
and this makes it even worse.
Overloading a cast operator at file scope could help me, but this
is not possible.
Also, an explicit cast like "baseptr1 = (Ptr<Base>) derivedptr1;" is
disallowed.
Can someone tell me how to resolve the problem? Is the standard
adapted in any way to resolve the problem?
Thanks in advance,
Johan
*/
#include <iostream.h>
class Base { };
class Derived : public Base { };
template <class Type> // smart pointer class definition
class Ptr
{
public:
Ptr(Type* ptr1) : ptr(ptr1) { }
private:
Type* ptr;
};
/*
operator Ptr<Base> (Ptr<Derived> derivedptr)
{
return (Ptr<Base>) derivedptr;
}
// overloading a cast operator at file scope is not possible
*/
main()
{
Base abase;
Derived aderived;
// with ordinary pointers:
Base* abasep1 = &abase;
Derived* aderivedp1 = &aderived;
abasep1 = (Base*) aderivedp1; // explicit casting is superfluous
abasep1 = aderivedp1;
// with smart pointers:
Ptr<Base> abaseptr1 = &abase;
Ptr<Derived> aderivedptr1 = &aderived;
// abaseptr1 = (Ptr<Base>) aderivedptr1; // not allowed
// abaseptr1 = aderivedptr1; // not possible because I'm
// unable to provide a cast operator
return 0;
}
-----------------------------------------------------------------------
Johan Vanslembrouck - SE99 Tel : +32 3 2407739
Alcatel Bell Telephone Telex : 72128 Bella B
Francis Wellesplein 1 Fax : +32 3 2409932
B-2018 Antwerp e-mail : jvsb@sebb.bel.alcatel.be
Belgium
-----------------------------------------------------------------------