teaching machines

CS 330 Lecture 27 – Polymorphism

April 10, 2015 by . Filed under cs330, lectures, spring 2015.

Agenda

TODO

Intentions

Theorize This

On your own, generate a theory for how dynamic dispatch might work? Given a reference/pointer to a supertype, how is it that we end up calling the right method in the subtype?
Persuade your neighbor that you are right.

What Does This Do?

  1. #include <iostream>
    
    class Super {
      public:
        void print() { 
          std::cout << "in super" << std::endl;
        }
    };
    
    class Sub : public Super {
      public:
        void print() { 
          std::cout << "in sub" << std::endl;
        }
    };
    
    int main(int argc, char **argv) {
      Sub a;
      a.print();
    
      Super b;
      b.print();
    
      Super *c = new Sub();
      c->print();
      delete c;
    
      return 0;
    }

  2. class IntAndDouble {
      public:
        IntAndDouble() {}
      private:
        double d;
        int i;
    };
    
    int main(int argc, char **argv) {
      std::cout << sizeof(IntAndDouble) << std::endl;
      return 0;
    }

  3. class TwoIntsAndDouble : public IntAndDouble {
      public:
        TwoIntsAndDouble() {}
      private:
        int j;
    };
    
    int main(int argc, char **argv) {
      std::cout << sizeof(TwoIntsAndDouble) << std::endl;                                                                                             
      return 0;
    }

  4. class IntAndDouble {
      public:
        IntAndDouble() {}
        virtual int Get() const {
          return i;
        }   
      private:
        double d;
        int i;
    };
    
    class TwoIntsAndDouble : public IntAndDouble {
      public:
        TwoIntsAndDouble() {}
        virtual int Get() const {
          return j;
        }   
      private:
        int j;
    };
    
    int main(int argc, char **argv) {
      std::cout << sizeof(IntAndDouble) << std::endl;
      std::cout << sizeof(TwoIntsAndDouble) << std::endl;                                                                                                                             
      return 0;
    }

A Virtual Class

class A {
  virtual void f();
  virtual void g(int);
  virtual void h(double);
  int a;
}

class B : public A {
  void g(int); // overrides A::g
  virtual void m(B *);
  int b;
}

class C : public B {
  void h(double); // overrides A::h
  virtual void n(C *);
  int c;
}