My experience so far is mostly in Java but i'm trying to learn C++ and i'm still struggling to understand pointers, overloads etc. Forgive me about the title but i didn't know how to present my problem. Anyway i came across this exercise while studying and i would like some help. The exercise provides a class Container and a main() and i'm supposed to extend the Class and make the main() work to provide the proper result.
template <typename T>
class Container
{
protected:
T * storage;
size_t num_items;
size_t storage_size;
public:
virtual void operator += (const T item) { }
virtual ~Container() { }
Container() : storage(nullptr), num_items(0), storage_size(0) { }
T operator [] (size_t index)
{
if (num_items==0)
return T(0);
return storage[index<num_items?index:num_items];
}
inline size_t size() { return num_items; }
};
void main(int argc, char* argv[])
{
Container<long> * store = new Container_ex(); // I'm suppose to fill this gap
---------------
size_t num_data;
cin >> num_data;
for (size_t i=0; i<num_data; i++)
{
long item;
cin >> item;
*store+=item;
}
for (size_t i=0; i<store->size(); i++)
std::cout << (*store)[i] << " ";
std::cout << std::endl;
delete store;
}
So far i've done this. The problem lies when i try to overload += cause i get an exception error (this->storage was nullptr)
but in any case i don't understand the use of storage completely in this exercise so i would appreciate any help.
class Container_ex : public Container<long> {
public:
Container_ex() : Container() {}
~Container_ex() { delete[] storage; }
void operator += (const long item)
{
*storage = const_cast<long&>(item);
*storage = *storage + item;
num_items = num_items + 1;
storage_size = storage_size + 1;
}
};