0

My professor is known for his vagueness in assignment instructions. He wants us to create two template classes in c++ using pointer type private members as an array and then removing objects of that array, adding things to the array, etc.. However, isn't it impossible to initialize the pointer array to the correct size without somehow getting an input from the console or the program to determine how many pointers to create? I would email him and ask but he has become sick and his email response time has slowed to something like 2 days. Here is one of the two classes we are given :

template<class T>
class Stack{
private:
    T*  StackArray;

public:
    Stack();
    ~Stack();

    void push(const T&); //pushes a data at the top
    T pop(); //deletes data from the top and returns the data
    bool isEmpty();//checks if the stack is empty
    T top();//returns the top of the stack
};

I have researched to see if there was a function like get.length() that could be applied but I couldn't find anything. This isn't an array type so I can't use the functions I found. Is the only way this class will work if I also take a size input from the user? Thanks in advance.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 1
    You can dynamically allocate memory with `new`. A pointer can point to contiguous memory. – cigien Apr 30 '20 at 16:35
  • What you are looking for is called a dynamic array. You can see how those grow here: https://stackoverflow.com/questions/1350630/how-to-expand-an-array-dynamically-in-c-like-in-vector – NathanOliver Apr 30 '20 at 16:37
  • 1
    Your professor wants you to correctly implement an array whose size grows and shrinks as needed, and ***not*** to create an array of some known size, which never changes after creation. Any "solution" that uses a fixed size array will likely result in a failed grade. This kind of a problem is given, as an example, in every C++ textbook, so you should be able to pretty much take the examples in your textbook, with just a few modifications. – Sam Varshavchik Apr 30 '20 at 16:40
  • That's what I was asking. We did dynamic allocation a few weeks ago, and in our class you can never tell how much he wants you to change the template code he gives us. Thank guys, wasn't very sure. – killerkody gaming Apr 30 '20 at 16:43
  • 2
    In real life, most (sane) people would just use `std::array` and/or `std::vector`. – Jesper Juhl Apr 30 '20 at 17:06
  • "*in our class you can never tell how much he wants you to change the template code he gives us*" - he probably doesn't want you to change it at all (unless he explicitly says otherwise), and to just *implement* whatever *declarations* he gives you. – Remy Lebeau Apr 30 '20 at 17:25
  • @JesperJuhl I agree, but even though this is my second CSC class, we still have been told to not use vectors because we haven't covered them. – killerkody gaming May 01 '20 at 02:26

0 Answers0