MC logo

Base Class Init, Virtual Functions

  Practice Questions

Consider:

#include <iostream>

using namespace std;

class Nine {
    protected:
        int pwr_level;
    public:
        Nine(int n = 0) { 
                pwr_level = n; 
                cout << "Nine(" << n << ")" << endl;
        }
        void up(int n) { pwr_level += n; }
        virtual void down(int n) { pwr_level -= n; }
        void print() { cout << "[" << pwr_level << "]" << endl; }
};

class Ten: public Nine {
    protected:
        int boron;
    public:
        Ten() { boron = 2; }
        Ten(int b): Nine(b) { boron = 3*b + 7; }
        void up(int n) { pwr_level *= n; }
        virtual void down(int n) { pwr_level /= n; }
        void collect() { 
                boron += pwr_level;
                pwr_level = 0;
        }
};

main()
{
        Nine *n = new Ten(10);
        Ten t;

        t.up(3);
        t.down(2);
        t.print();

        n->up(3);
        n->down(2);
        n->print();
}

What does the code print?

What would happen if we added the statement n->collect() to the main function?


<<Construction and Destruction II Answer