i thought i knew c++ better than this but i obviously dont. basically, i want to know what function i could add to MMObjectPtr that replaces the functionallity of cast() so that instead of b=i.cast(); i can say b=i; anyway heres the code, i know ive got a memory leak but this is just demonstational code.
<edit>
never mind, ive just found the syntax for the casting operator, allows you to cast any type into another
operator T*() {return ptr;}
replaces cast() very nicely
</edit>
Code:
#include <iostream>
using namespace std;
class MMObject {
private:
int count;
protected:
MMObject() : count(0) {}
public:
void AddRef() { count++;}
void ReleaseRef() {count--;}
};
template<class T>class MMObjectPtr
{
private:
T *ptr;
public:
MMObjectPtr() : ptr(NULL) {}
~MMObjectPtr() { if(ptr != NULL) ptr->ReleaseRef(); }
T *cast() const { return ptr; }
MMObjectPtr(T *p) { *this=p; }
MMObjectPtr<T> &operator=(T *p) {
if(ptr !=NULL) ptr->ReleaseRef();
ptr=p;
if(ptr !=NULL) ptr->AddRef();
return *this;
}
MMObjectPtr<T> &operator=(MMObjectPtr<T> &p) {*this=p.ptr;}
T *operator->() const { return ptr; }
};
class base : public MMObject
{
public:
virtual void a()=0;
};
class imp : public base
{
public:
void a() {cout << "Youve called imp::a()" << endl;}
};
int main()
{
MMObjectPtr<base> b;
MMObjectPtr<imp> i;
i=new imp;
b=i.cast();
b->a();
return 0;
}