A stands for Abstract: it is useful when there is an abstraction.
Given your cat and dog, a cat is a pet. A dog is also a pet. If you have no "just" pets, every pet is actually a cat or a dog, then "pet" is an abstraction.
You can then write "class cat : public pet" and "class dog : public pet", and if, in your universe, every pet can cry, then you can define "virtual void cry() = 0" as a public member function of class pet.
Then, if you have a part of the program that
uses the abstraction, e.g. some function, say hurt(), that takes a pet and makes it cry, you'd have to write it once, without having to write an individual hurt() function for every kind of pet you have:
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
|
#include<iostream>
using namespace std;
class pet {
public:
virtual void cry() = 0;
};
class cat : public pet {
public:
void cry() { cout << "MEOOOOOOOOOOOOOOOOOOW!\n"; }
};
class dog : public pet {
public:
void cry() { cout << "WOOOOOOOOOOOOOOOOOOOF!\n"; }
};
void hurt(pet& p)
{
p.cry();
}
int main()
{
cat kitty;
dog puppy;
hurt(kitty);
hurt(puppy);
}
|