-1

I saw this question online, and i would like to know if i am doing this correctly or not. The site does not list the answer or guides.

The question

Write the declaration only for the abstract class Animal. Animal should contain attributes for name and age, and functions display, setFields and concrete. Write the declaration and implementation, of a class Tiger derived from Animal, with the Tiger having overridden functions which were appropriate, use the base class one. The Tiger has additional data fields associated with strips(an integer) and tailLength.

I would appericate, if you can tell if i am doing it correctly.

Animal class

 class Animal{
  private:
  string name;
  int age;
  public:
  void display();
  void setFields(string, int);
  void concrete();
};

Tiger class

 class Tiger:public Animal{
 private:
 int strips;
 int tailLength;
 public:
 void display();
 void setFields(string, int, int, int);
};
M.A
  • 973
  • 2
  • 11
  • 20

2 Answers2

3

If you want derived classes to be able to override base class methods, you need to make these virtual. Otherwise your derived classes will just hide the name of the methods you were intending to override. You should also provide a virtual destructor.

class Animal{
  private:
  std::string name;
  int age;
  public:
  virtual void display();
  virtual void setFields(string, int);
  virtual void concrete();
  virtual ~Animal() {}
};

It is not clear what the assignment means about an abstract base class. Usually this means at least one pure virtual method is not implemented. But the assignment mentions using the base class implementations where appropriate, which means you should provide some implementations in Animal.

Community
  • 1
  • 1
juanchopanza
  • 210,243
  • 27
  • 363
  • 452
2

An abstract class uses pure-virtual member functions:

class Animal{
  private:
  string name;
  int age;
  public:
  virtual void display() = 0;
  virtual void setFields(string, int) = 0;
  virtual void concrete() = 0;
  virtual ~Animal() { }
};

Not all of them would necessarily be pure virtual, but at least one of them has to be in order for the class to be considered abstract.

Vaughn Cato
  • 59,967
  • 5
  • 75
  • 116