Thread: Overloading -> operator

  1. #1
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002

    Overloading -> operator

    I've done a quick google and board search, but didn't turn up any promising results. What I'm trying to do is write a simple class, encapsulating a pseudo-Singleton pointer:
    class MySingleton
    	class Inst
    		Inst() {ptr = MySingleton::getInst();}
    		~Inst() {MySingleton::delRef(ptr);}
    		MySingleton* operator-> () {return ptr;}
    		MySingleton* ptr;
    	//some data members
    	static MySingleton* ptr;
    	static int* refCount;
    	static MySingleton* getInst();
    	static void delRef(MySingleton*& ref);
    	friend class Inst;
    Currently the class (the pseudo-singleton) just creates the object when getInst() is called and refCount == NULL; delRef checks to see if the pointer passed is a valid pointer to the singleton, and if it is, it decreases *refCount and sets the pointer to NULL, destroying the object/refCount if *refCount reaches zero.

    My goal is to create an Inst() class which will get a pointer on creation and release it on destruction, and allow the user to access the singleton's member variables through its -> operator, or something along those lines - but without allowing the user to ever access a pointer to the real thing. Aside from the -> operator, I was thinking of something like defining a conversion operator to MySingleton. Does anyone have ideas about how I might go about doing this?

    Heh nvm, I think I figured it out now (the -> operator really confuses me...). I just had to get operator-> to return a MySingleton* instead of reference, and declare Inst as a friend class of MySingleton ... Operators are so cool...

    I fixed the code to reflect my changes (also took out the checking for a valid pointer), for anyone who might be interested.

    Say, is that how smart-pointers work or something?
    Last edited by Hunter2; 05-10-2004 at 03:37 PM.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. unary operator overloading and classes
    By coletek in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2009, 02:14 AM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. Operator Overloading (Bug, or error in code?)
    By QuietWhistler in forum C++ Programming
    Replies: 2
    Last Post: 01-25-2006, 08:38 AM
  4. C++ Operator Overloading help
    By Bartosz in forum C++ Programming
    Replies: 2
    Last Post: 08-17-2005, 12:55 PM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM