Sunday, December 17, 2017

Using Abstract Superclass

In this code, Mammal and Fish will inherit from the abstract super class Animal and we add instances of Mammmals and Fish to a vector of Animals. This necessitates a couple of small changes to the syntax; (1.) the vector will now have to be defined as a vector of pointers to the Mammals and Fish and (2.) the call to the respire() method will need to use the arrow to dereference off the pointer rather than the dot.

After creating the vector, the Animal and Fish references will be accessed and the respire() method executed on each instance using the new for loop and then the STL for_each method.
#include <iostream>
#include <vector>
using namespace std;

class Animal {
  public:
    virtual string respire() = 0;
};

class Mammal:public Animal {
  public:
    string respire() {
      return "huff, puff";
    }
};

class Fish: public Animal {
  public:
    string respire() {
      return "bubbles";
    }
};

int main() {
  Mammal dog, cat;
  Fish goldfish;
  vector<Animal *> animals = {&cat, &dog, &goldfish};
  for (auto a : animals) {
    cout << a->respire() << endl;
  }

  for_each(
    animals.begin(), 
    animals.end(), 
    [](Animal* x){cout << x->respire() << endl;});
}
$ g++ -std=c++14 -c -o Animals.o Animals.cpp
$ g++ -o Animals Animals.o
$ ./Animals
huff, puff
huff, puff
bubbles
huff, puff
huff, puff
bubbles
$