Recently, I was tasked with when I had to implement something similar to the following:
There are some animals with certain attributes, for example:
Dog1: name: tery, color: white, fav drink: grape juice
Dog2: name: chiva, color: black, fav drink: lemonade
Bird1: name: tweety, canfly: yes, cansing: no
Bird2: name: parry, canfly: no, cansing: yes
How could you do this in C ++ effectively taking advantage of OOP?
I did something like this:
class Animal {
Animal(...);
...
public String getName() const;
public void setName(string s);
...
private:
String name;
}
class Bird : public Animal {
Bird(...);
public bool canFly() const;
public void setCanFly(bool b);
...
private:
bool canFly;
bool canSing;
}
class Dog : public Animal {
...
}
The problem with this implementation is that I cannot use polymorphism:
Animal* p = new Anima(...);
...
p->canFly();
and I have to use casting:
((Bird*)p)->canFly();
In the end, I was criticized for not using virtual functions in the base class and using throws instead of OOP.
, , , getName() , . canFly , .
, () , , :
bool Dog::canFly () const {
return false;
}
, ?