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;
}
(this->storage was nullptr)
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;
}
};
Your pointer needs to point on a valid memory address before you can do anything with it. If it doesn't, it leads to undefined behavior that can end in a crash of your application, for example.
But when do you need to do it ? Certainly not in the operator overload. When you create an object, you must ensure that it is in a valid state. It means either setting it to nullptr
so it is a null pointer, or allocating memory for it.
If you do it in operator overload, how can you be sure that operator overloading will be used ? Maybe the user just wants doing []
. So you have to make a constructor allocating memory for your pointer. Or, better, use smart pointers that will save your life and provent headaches, especially if you come from a language where there is no explicit pointer like Java.
Finally, there are some great books to learn C++ better than the course you use.