Archived

This topic is now archived and is closed to further replies.

farmersckn

Overloading the -> operator

Recommended Posts

If I have a generic pointer template,
    
template <class T>
class CPointer
{
   CPointer ();
   ~CPointer ();
   T *lpPointerData;
}
    
How would I make use of the -> operator, assuming I want to use it to reference member functions and such? farmersckn

Share this post


Link to post
Share on other sites
You could overload the -> operator if you really want but as it sits right now, the . operator will do what you want. If you really want to use the -> operator, declare your instances like this:

int f = 8;
CPointer *myVar = new CPointer;
...
myVar->lpPointerData = &f;

As it sits though, you can do this:

int f = 8;
CPointer myVar;
...
myVar.lpPointerData = &f;

I may have messed up the declaration, I''m not too familiar with templates. Essentially, the -> operator is the same as the . operator but used for pointers to class instances (and maybe pointers to structs too). Remember, if you use the first way, you have to delete myVar (or you get memory leaks).

I hope I''ve actually answered your question instead of bizzarely misinterpreting it.

-Goku

Share this post


Link to post
Share on other sites
You could always use std::auto_ptr - it probably does what you want.

Otherwise, here''s an example:

    

template <class PTR_TYPE>
class SmartPtr
{
private:
PTR_TYPE *iPtr;
public:
explicit SmartPtr(PTR_TYPE* in=0) { iPtr = in }
~SmartPtr() { delete iPtr; iPtr = 0; }

// note use of const method returning pointer to non-const

// object - implication is the POINTER is const but

// the object being pointed to may not be being referred

// to in a const manner

PTR_TYPE* operator->() const { return iPtr; }
};

class MyType; // with definition


SmartPtr<MyType> thingy( new MyType );

thingy->DoSomething();



You''ll probably want to add some other member functions as well.
Take a look at std::auto_ptr in the header file for ideas.

Share this post


Link to post
Share on other sites