Link to home
Create AccountLog in
Avatar of oggiemc
oggiemcFlag for Ireland

asked on

Template storage container

Hello all,

Can someone explain the following code for me line by line please? In particular, im having dificulty understanding the addElement function..Thanks
template<class T, int size>
class Storage
{
T values[size];
int next;
public:
T& operator [](int index)
{
return values[index];
}
bool addElement(T value)
{
if (next>size) return false;
values[next++]=value;
return true;
}
int getSize() { return next-1; }
};

Open in new window

Avatar of Subrat (C++ windows/Linux)
Subrat (C++ windows/Linux)
Flag of India image

This is a class template.
>>if (next>size) return false;
here whts value of next????
next isn't initialized.So it's a bad programming....

If want to know about class template follow:http://www.cplusplus.com/doc/tutorial/templates/

and tell us if u want any help.
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of oggiemc

ASKER

thanks for reply infinity,

>>(a) the 'next' data member is never initialized. There should be a constructor in the class that initializes it to 0.
Can i not just do "int next = 0;" ?

>>(b) the operator[] never checks whether the index is out of bounds or not (either lower than 0, or larger than or equal to 'next').
i thought 'next' was the index?:
>>and an int 'next' that holds the index of the next free position in the array (ie. one after the last element in the array).



if (next>size) return false;
values[next++]=value;
return true;

 
would this do the same job? :

if (next>size) {return false;}
else {values[next++]=value;
return true;}

Thanks







SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account