Polymorphism Exercises

  < Previous  Next >
  1. Share with your neighbor(s) what is polymorphism and why we would want to use it.
  2. Write a SHORT C++ program that has a polymorphic method named print() that prints out its class name. Clearly label (with C++ comments) each of the four essential ingredients for having a polymorphic method call:
    1. Inheritance
    2. Virtual method (base class)
    3. Virtual method overridden in derived class
    4. Pointer or reference of the base class type, but pointing to/referencing the derived class
  3. Can a constructor be virtual? Share your thoughts about this with your neighbor(s).
  4. Without compiling the code, determine what the output of the following main function will be.
    #include <iostream>
    using namespace std;
    
    class Base {
    public:
        Base() {}
        virtual void A() { cout << "Base A\n"; }
        void B() { cout << "Base B\n"; }
    };
    
    class One : public Base {
    public:
        One() {}
        void A() { cout << "One A\n"; }
        void B() { cout << "One B\n"; }
    };
    
    class Two : public Base {
    public:
        Two() {}
        void A() { cout << "Two A\n"; }
        void B() { cout << "Two B\n"; }
    };
    
    int main() {
        Base* base0 = new Base;
        Base* base1 = new One;
        Base* base2 = new Two;
        
        base0->A();
        base0->B();
        cout << endl;
    
        base1->A();
        base1->B();
        cout << endl;
    
        base2->A();
        base2->B();
        cout << endl;
    
        return 0;
    }
    

Last Modified: