Skip to main content
gamedev.net
🔒 Locked

Template Operator Overloading [c++]

Started by maxpenguin Sep 22, 2006 at 6:32 PM 2 replies 2k views
Original Post
maxpenguin
maxpenguin
Hi All, I am implementing (for educational reasons) a Templated dynamic sized list in C++. I've come across a problem with operator overloading, and I can't see what I am doing wrong. I have my template class defined like this:

template<typename Type> class mylist
{
public:
	mylist<Type>()
	{
		// allocate the initial storage (default to 10)
		initialize(10);
	}

	mylist<Type>(int capacity)
	{
		// allocate the initial storage
		initialize(capacity);
	}

	~mylist<Type>()
	{
		m_count		= -1;
		m_capacity	= -1;
		delete[]	  m_data;
		m_data		= NULL;
	}

	void Add(const Type &item);

	Type operator[] (int index);

	Type getVal(int index)
	{
		return m_data[index];
	}

private:
	Type*	m_data;
	int	m_count;
	int	m_capacity;

	void	initialize(int capacity);
	void	resize();
};

// irrelevant implementations snipped

template<typename Type> Type mylist<Type>::operator[] (int index)
{
        // leave out bounds checking for now

	return m_data[index];
}


And I am using it like this:

	mylist<int>* theList = new mylist<int>();

	int count = 50000;
	
	for (int i = 0; i < count; ++i)
	{
		theList->Add(i * 3);
	}

	int val = -1;

	for (int i = 0; i < count; ++i)
	{
		val = theList;
		cout << val << endl;
	}

	delete theList;


I get a compiler error: Error 1 error C2440: '=' : cannot convert from 'mylist' to 'int' On the "val = theList;" line. I can't see what I am doing wrong here? Any ideas? Thanks!
Excors
Excors
You declared theList as a mylist* - i.e. a pointer to a mylist, so theList is accessing it as an array of mylist objects. (*theList) ought to call mylist::operator[].
maxpenguin
maxpenguin
Wicked, thanks! That was silly of me [looksaround].

Thanks again [grin].
Zahlman
Zahlman
This is one of the many reasons for not using pointers where you don't need them. A plain old instance of Mylist would work just fine here; the whole idea with container classes is to have them do memory management in such a way that you can treat them *as if* all the data were on the stack, without it actually being there.

BTW, it's not a list you're re-implementing this way but a vector :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.