Saturday, December 16, 2017

C++ Constructor Initializer List with Inheritance

This code has Penguin and Bluejay inheriting from Bird and each displaying specialized functionality particular to their species; in this code, Bluejay can fly and Penguin can swim but not vice-versa.
#include <iostream>
using namespace std;

class Bird {
  private:
    bool can_fly, can_walk, can_swim;
  public:
    // constructor definition using "initializer list"
    Bird(bool flyer, bool walker, bool swimmer): 
      can_fly(flyer), can_walk(walker), can_swim(swimmer) {} 

    string walk(int steps) {
      if (can_walk) return go(steps, "hop");
      return "";
    }
    string fly(int flaps) {
      if (can_fly) return go(flaps, "flap");
      return "";
    }
    string swim(int kicks) {
      if (can_swim) return go(kicks, "kick");
      return "";
    }
    string go(int steps, string flap) {
      string comma = "";
      string going = "";
      for (int x = 0; x < steps; x++) {
        going += (comma + flap);
        comma = ", ";
      }
      return going;
    }
};

class Penguin : public Bird {
  public:
    // Penguin initialized with super class as the "initializer list"
    Penguin():Bird(false, true, true){}; 
};

class Bluejay : public Bird {
  public:
    // Bluejay initialized with super class as the "initializer list"
    Bluejay():Bird(true, true, false){}
};

int main() {
  Penguin p;
  cout << "Penguin swim 5 " << p.swim(5) << endl; 
  cout << "Penguin fly 3 "  << p.fly(3)  << endl; 
  cout << "Penguin walk 4 " << p.walk(4) << endl;
  Bluejay b;
  cout << "Bluejay walk 2 " << b.walk(2) << endl; 
  cout << "Bluejay swim 4 " << b.swim(4) << endl; 
  cout << "Bluejay fly 3 "  << b.fly(3)  << endl;
}

Commands to compile, link and run the code followed by the program output
$ g++ -std=c++14 -c -o Bird.o Bird.cpp
$ g++ -o Bird Bird.o
$ ./Bird
Penguin swim 5 kick, kick, kick, kick, kick
Penguin fly 3 
Penguin walk 4 hop, hop, hop, hop
Bluejay walk 2 hop, hop
Bluejay swim 4 
Bluejay fly 3 flap, flap, flap