Overloading the -> operator

Started by
1 comment, last by farmersckn 23 years, 6 months ago
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
Yesterday is the past, tomorrow is the future. Today is a gift, that is why we call it the present.
Advertisement
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
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 definitionSmartPtr<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.

This topic is closed to new replies.

Advertisement