Having some trouble with a homework assignment, so any help would really be appreciated. I'm not just asking for an answer, trying to learn :)
Problem:
When a function that needs to return something “panics”, return the ‘m_errobj’ member.
It is with an arraylist class. This is what I am given:
1 2 3 4 5 6 7 8 9
template <typename T>
class ArrayList
{
private:
int m_size; // current number of elements
int m_max; // maximum capacity of array m_data
T* m_data; // array to store the elements
T m_errobj; // object to return in case of error
I made the public function find that returns the index number of x, which does what it should, but I cannot figure out how to handle errors. The assignment creates a arraylist of strings. Which if I understand it correctly(which I may not) m_errobj is a string, so I cannot return a string as an int.
1 2 3 4 5 6 7 8 9 10
template <typename T>
int ArrayList<T>::find(const T& x)
{
for(int k=0;k<m_size;k++)
if(m_data[k]==x)
return k;
// else
// return -1; or return m_errobj; ?
// not sure how to return my error as m_errobj if x is not found
}
I know it says control reaches end of non-void function because if x is not present it will not have anything to return.
Any pointers in the right direction would be nice.
Given the class declaration, find should return an object of type T.
Returning m_errobj in an error situation, m_errobj is also of type T.
So find should look like this:
1 2 3 4 5 6 7
template <typename T>
T ArrayList<T>::find(const T& x) // return type of function is T
{ for(int k=0;k<m_size;k++)
if (m_data[k]==x)
return m_data[k]; // return the element (not the index)
return m_errobj; // return the error object
}
Not clear how m_errobj is initialized, but I would assume it is passed in through the class constructor (not shown).
Thanks for the reply. Apparently I don't read directions very well though. It was supposed to return an int of -1 if there was an invalid entry. The whole return m_errobj part is confusing though, it is never initialized anywhere in the assignment so I'm not really sure where he was going with it.
I appreciate the response though, free help is always awesome, thank you.