1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <cstdio>
#include <string>
using namespace std;
// Base class
class Animal {
string _name;
string _type;
string _sound;
// private constructor prevents construction of base class
Animal() {};
protected:
// protected constructor for use by derived classes
Animal(const string & n, const string & t, const string & s)
: _name(n), _type(t), _sound(s) {}
public:
void speak() const;
const string & name() const { return _name; }
const string & type() const { return _type; }
const string & sound() const { return _sound; }
};
void Animal::speak() const {
printf("%s the %s says %s\n", _name.c_str(), _type.c_str(), _sound.c_str());
}
// Dog class - derived from Animal
class Dog : public Animal {
public:
Dog(string n) : Animal(n, "dog", "woof"){};
};
// Cat class - derived from Animal
class Cat : public Animal {
public:
Cat(string n) : Animal(n, "cat", "meow"){};
};
// Pig class - derived from Animal
class Pig : public Animal {
public:
Pig(string n) : Animal(n, "pig", "oink"){};
};
int main(int argc, char ** argv) {
Dog d("Rover");
Cat c("Fluffy");
Pig p("Arnold");
d.speak();
c.speak();
p.speak();
}
| |