Thread: Overloading the [] operator trouble

  1. #1
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330

    Overloading the [] operator trouble

    I'm trying to overload the [] operator, so I made a simple vector class. I was looking through some of the directx headers and how they overloaded the operator. I made a completely const version that returns the value at a certain pos, and a non-const one that returns a pointer to a pos in the array (I think...) Anyway, it sorta works. On my machine it prints V[1] as 15 and V[0] as 34, but the program always crashes and I'm not sure why. Any help would be great, thanks!

    Here's the code:

    Code:
    #include <iostream.h>
    
    class CVect
    {
    private:
    	int *dat;
    	int len;
    public:
    
    	CVect ();
    	CVect (int);
    	CVect (CVect&);
    
    	~CVect () {};
    
    	const int operator [] (int) const;
    	int get_len (void) const;
    
    	int& operator [] (int);
    	void set_len (int);
    
    };
    
    const int CVect::operator [] (int a) const {
    	return dat [a];
    }
    
    int& CVect::operator [] (int a) {
    	return *(dat + (a * sizeof (int)));
    }
    
    inline int CVect::get_len (void) const {
    	return len;
    }
    
    inline void CVect::set_len (int l) {
    	len = l;
    }
    
    CVect::CVect () : len (1)
    {
    	dat = new int (len);
    }
    
    CVect::CVect (int l) : len (l)
    {
    	dat = new int (l);
    }
    
    int main (void)
    {   
    	CVect V (10);
    
    	V[1] = 16;
    	V[0] = 34;
    
    	for (int i = 0; i < V.get_len() - 1; ++i)
    		cout << V[i] << endl;
    
        return (0);
    }
    Last edited by rmullen3; 08-01-2002 at 12:46 PM.

  2. #2
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    dat = new int (_len);

    try

    dat = new int[[_len];

  3. #3
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330
    lol... Can't believe I didn't catch that.. guess I coded it too fast. Thanks for pointing it out though!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help on understandind arrays
    By C++mastawannabe in forum C++ Programming
    Replies: 9
    Last Post: 06-16-2007, 10:50 PM
  2. Overloading [] and Assignment
    By Mastadex in forum C++ Programming
    Replies: 6
    Last Post: 12-24-2006, 12:22 PM
  3. crazy = and [] operator overloading question
    By jarro_2783 in forum C++ Programming
    Replies: 7
    Last Post: 09-15-2006, 08:56 PM
  4. overloading []
    By pktcperlc++java in forum C++ Programming
    Replies: 3
    Last Post: 03-02-2005, 09:09 PM
  5. Overloading the [] operator
    By Strahan in forum C++ Programming
    Replies: 3
    Last Post: 02-25-2002, 03:08 PM