Smart Pointer that supports subclassing

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Until now all smart pointer implementations that I
have seen didn’t support assignment between base and derived
class pointers. Here is an implementation that does support it.
I give you two implementations of smart pointers:

1) Ptr<T> – This smart pointer assumes that ‘T’ support reference
counting by deriving from IRefCount (which is also supplied).

2) SmartPtr<T> – This smart pointer is more generic than Ptr<T>
while not assuming anything about the type ‘T’. Being more generic
costs having a small reference object created for each referenced
object or type.

The following source code demonstrates the use of the two types
of smart pointers templates.


#include <string>
#include <iostream>
#include "ptr.h"
#include "smartPtr.h"

using namespace std;

class Object;
class Host;

typedef Ptr<Host>			PHost;
typedef Ptr<Object>			PObject;

class Object : public IRefCount {
	public:
		Object (int id, const string& name) : m_name(name), m_id(id) {};
		const string& GetName () { return m_name; }
	protected:
		string	m_name;
		int		m_id;
};

class Host : public Object {
	public:
		Host (int id, const string& name, const string& hostName):
				m_hostName(hostName), Object (id, name) {};

	protected:
		string	m_hostName;
};

// The following two classes do not carry any
// reference counting inteface.
class Base {

};

class Derived : public Base {

};

typedef SmartPtr<Base>		PBase;
typedef SmartPtr<Derived>	PDerived;


void PrintName (PObject pObj)
{
	cout << pObj->GetName() >> endl;
}

// testSmartPtr
//
// demonstrate the SmartPtr<T> template. The
// Base and Derived classes are simple classes
// that don't support any reference counting.
//
void testSmartPtr ()
{
	PDerived pDerived2;
	PBase pBase;

	PDerived pDerived = new Derived;

	// The Ptr<T> supports subclassing
	pBase = pDerived;
	pDerived2 = (PDerived&)pBase;
}

// testPtr
//
// demonstrate the Ptr<T> template. The Ptr<T>
// assumes that the referenced class 'T' supports
// the reference counting interface IRefCount.
//
void testPtr ()
{
	PHost pHost2;

	PHost pHost = new Host (1, "Wks5", "");

	// The Ptr<T> supports subclassing
	PObject pObject = pHost;
	pHost2 = (PHost&)pObject;
	PrintName (pHost2);
}

/**************************************************************
 | NAME: main
 **************************************************************/
void main ()
{
	testSmartPtr ();
	testPtr ();
}

Downloads

Download demo project – 6 Kb
Download source – 3 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read