A Smart Pointer Class for Subclass Pointers

The SmartPtr
class by Stefan Tchekanov
works nicely for homogenous class
objects but it does not allow assignment between base and derived
class pointers. I am presenting here a simple template class that
performs reference counting garbage collection and supports subclass
pointers. The example that follows explains the use of this class:


class B {


};


class A : public
B {
A(const char* s1, const char* s2);
void foo() { … }


};


P<B>
a = new A("Smart", "Pointer");
P<B> b =
a;
P<A> c(a.Reference());
a
= 0;
c->foo();


In this example, a derived class (A) object pointed by a base
class (B) smart pointer a is
assigned back to c — a smart
pointer to the derived class (A). The reference counting and
automatically object destruction is similar to other smart pointer
implementations (e.g. Stefan’s RefCountPtr),
but in our case it allows access derived class members (which do not
have to be overloaded virtual functions) from a base class smart
pointer.


However, this added flexibility comes at a cost. The assignment
from pointers a to c
in the example above does not conduct type checking. When "down
casting" a smart pointer from super (base) class to subclass
(derived) class, it is your responsibility to make sure that the
pointed object is indeed a subclass object. If anyone out there has a
fix for this drawback, please post.

Downloads

Download the demo project – 4 Kb

Download the source – 1 Kb

More by Author

Previous article
Next article

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read