Try alot but don't know how to fix this code anyone ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Try alot but don't know how to fix this code anyone ?

Question: You are making a queue management system and need to support different data types - for example, you should be able to queue names which are strings or integer numbers. So, you decide to make a Queue class template, which will store an array for the queue, and have add() and get() methods. You first create a class for integers only, to see if it works. The given code declares a Queue class with the corresponding methods for integers. Change the class to convert it into a class template, to support any type for the queue and so that the code in main runs successfully. Code: #include <iostream> using namespace std; //change the class to a template class Queue { private: int *arr; int count; public: Queue(int size) { arr = new int[size]; count = 0; } void add(int elem) { arr[count] = elem; count++; } void get(int index) { cout << arr[index]<<endl; } }; int main() { Queue<string> q(4); q.add("James"); q.add("Andy"); q.add("Amy"); q.get(2); Queue <int> n(2); n.add(42); n.add(33); n.get(1); return 0; }

23rd Jul 2021, 2:49 PM
Farhan Anwar
Farhan Anwar - avatar
1 Answer
+ 3
Inheritance is likely to be overkill for this exercise, and you immediately stumbled into two pitfalls. Private members of a class are not accessible from the outside at all, so Queue has no access to "arr" and "count" from integer. If a derived class needs access to members from the base class, those should be protected instead. Also, when deriving from a template class, the derived class has to be a template too, or derive from an explicit instantiation of the base class, e.g. integer< int >. The last thing to note is that only the array of elements to be stored needs to be templated, the "count" variable should remain an integral type. A counter variable, which purpose is to keep track of a number, of type string would not make much sense when instantiating the class for std::string, for example. Edit: I can see you changed the code, but now completely removed the template. The class should be parameterized by one template type, and every occurence of "int" related to "arr" replaced by the parameter.
23rd Jul 2021, 3:21 PM
Shadow
Shadow - avatar