0

Why q2 is not able to call add function (inherited). But if i comment or remove print function add function can be called.

#include <iostream> using namespace std; class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } void add(int data) { queue[size] = data; size++; } void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout << endl; } }; //your code goes here class Queue2 : public Queue { private: int size; int* queue; public: Queue2() { size = 0; queue = new int[100]; } /*void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<endl; } cout << endl; }*/ }; int main() { Queue q1; q1.add(42); q1.add(2); q1.add(8); q1.add(1); q1.print(); Queue2 q2; q2.add(3); q2.add(66); q2.add(128); q2.add(5); q2.add(111); q2.add(77890); q2.print(); return 0; }

12th Dec 2020, 5:24 PM
Fgbgev
5 odpowiedzi
0
one of the reasons why you'd extend an existing class is to give new functionality to that existing class. I don't know why you need to create another dynamic array and size variable for Queue2. One of the reasons for using polymorphism is that you can have the same interface for different objects, and using that interface you can access different functionalities of different objects. to solve your problem, define print() as virtual in Queue class, then just override the print() in the Queue2. You don't need any constructor for Queue2 in this case. Complier will generate a default one which will call base class Queue(). Also mark Queue2 as "friend" in Queue class or have getter/setter for access to private members or mark the private members of Queue class as "protected".
12th Dec 2020, 5:41 PM
Flash
0
I created a new queue class so that i can represent a new queue and i want that print function in the Queue2 class bcoz i want every data of that object to be printed in new line since q1 doesn't print every data in new line
12th Dec 2020, 5:47 PM
Fgbgev
0
then you didn't get the point of learning inheritance and polymorphism and the purpose of that project to test your knowledge on these topics.
12th Dec 2020, 5:50 PM
Flash
0
K Flash tq for replying. I'll go through those topics again
12th Dec 2020, 5:54 PM
Fgbgev
0
btw, here are some of the ways to do this. You can ignore them if you want to solve it by yourself. solution - only inheritance https://code.sololearn.com/cA25A20a4A20/# solution - inheritance, and polymorphism https://code.sololearn.com/ca2a13a250A1/#
12th Dec 2020, 7:06 PM
Flash