CS 23
April 18, 1997
Public inheritance, because it yields the IS-A relationship between derived classes and the base class. Overridden virtual functions would also be necessary.
Yes. Here is a sketch of insert():
// Assume data members: List l and int count. Insert(int item, int pos) { validate pos against count; delete pos - 1 items from l, re-inserting each at tail; insert item; delete count - (pos - 1) items from l, re-insert each at tail; increment count; }delete() is similar.
A stack, because of expressions such as a * (b + c)
and
a + b * c
in which a stack's LIFO property is necessary in
positioning the operators in the correct order in the postfix expression.
A stack, because of its LIFO property.
Qinsert(int item) { pop everything from B and push onto A; push item onto A; } Qdelete(int &item) // Variation on the standard theme. { pop everything from A and push onto B; pop an item from B and return through item parameter. }
#include <iostream.h> class Base { public: void F(void) { cout << "Flyers in 4\n"; } virtual void G(void) { cout << "Flyers in 5\n"; } virtual void H(void) { cout << "Flyers in 6\n"; } }; class Derived : public Base { public: void F(void) { cout << "Penguins in 4\n"; } void G(void) { cout << "Penguins in 5\n"; } }; int main() { Base B; Base *p; Derived D; p = &B; p->F(); p->G(); p->H(); p = &D; p->F(); p->G(); p->H(); return 0; }This is printed:
Flyers in 4 Flyers in 5 Flyers in 6 Flyers in 4 Penguins in 5 Flyers in 6The program will not compile if private inheritance is used. The pointer p within main is not permitted to point to Derived class instance D since formerly public members of Base are no longer so.
class Queue { private: double data[MAX]; int head; // Index of next item to be deleted. int tail; // Index to use for next item to be inserted. int count; // Number of items in queue. public: Queue(void) : head(0), tail(0), count(0) { } int IsEmpty(void); int IsFull(void); double Head(void); void Insert(double item); void Delete(void); };Solution:
int Queue::IsEmpty(void) { return count == 0; } int Queue::IsFull(void) { return count == MAX; } double Queue::Head(void) { assert(!IsEmpty()); return data[head]; } void Queue::Insert(double item) { assert(!IsFull()); data[tail] = item; ++count; tail = ++tail % MAX; } void Queue::Delete(void) { assert(!IsEmpty()); --count; head = ++head % MAX; }