Runtime polymorphism and operator overload

160 Views Asked by At

The problem is that in main function pointer to abstract class list calls operator+ of this class. But how can I call overloaded operators from child classes (queue and stack) with pointer to parent class list

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

class list
{
public:
    list* head; 
    list* tail; 
    list* next; 
    int num;
    virtual ~list() {}
    list() { head = tail = next = NULL; num = 0; }
    virtual list operator+(int i) { return *this; };
    virtual int operator-() { return 0; };
};
class queue : public list
{
public:
    list operator+(int i);
    int operator-();
};

class stack : public list
{
public:
    list operator+(int i);
    int operator-();
};

int main()
{
    srand(time(NULL)); rand();
    list* p;
    queue q_ob;
    stack s_ob;
    char ch;
    for (;;)
    {
        cout << "Enter something else to stop.\nStack, Queue or ULL? (S/Q): \n";
        cin >> ch;
        ch = tolower(ch);
        if (ch == 'q')
            p = &q_ob;
        else if (ch == 's')
            p = &s_ob;
        else break;
        p + (rand() % 100);
    }
    cout << "Enter T to terminate\n";
    for (;;)
    {
        cout << "Remove from Stack, Queue or ULL? (S/Q):";
        cin >> ch;
        ch = tolower(ch);
        if (ch == 'q')
            p = &q_ob;
        else if (ch == 's')
            p = &s_ob;
        else break;
        cout << -(*p) << '\n';
    }
    return 0;
}

list queue::operator+(int i)
{
    list* item;
    item = new queue;
    if (!item)
    {
        cout << "Allocation error.\n";
        exit(1);
    }
    item->num = i;
    // put on end of list:
    if (tail)
        tail->next = item;
    tail = item;
    item->next = NULL;
    if (!head)
        head = tail;
    return *this;
}

int queue::operator-()
{
    int i;
    list* p;
    if (!head)
    {
        cout << "List empty.\n";
        return 0;
    }
    // remove from start of list
    i = head->num;
    p = head;
    head = head->next;
    delete p;
    return i;
}

list stack::operator+(int i)
{
    list* item;
    item = new stack;
    if (!item)
    {
        cout << "Allocation error.\n";
        exit(1);
    }
    item->num = i; // put on front of list
    // for stack - like operation
    if (head)
        item->next = head;
    head = item;
    if (!tail)
        tail = head;
    return *this;
}

int stack::operator-()
{
    int i;
    list* p;
    if (!head)
    {
        cout << "List empty.\n";
        return 0;
    }
    // remove from start of list:
    i = head->num;
    p = head;
    head = head->next;
    delete p;
    return i;
}
0

There are 0 best solutions below