2

I am learning about virtual functions and abstract classes and it seems that I have a difficulty in comprehending something. Let's say I have this code:

class animal {
  public:
    virtual void show()=0;
};

class dog : public animal {
  int weight;
};


int main()
{
  //animal a;
  dog d;
  return 0;
};

I understand how animal a is incorrect because the animal class is abstract and I am not allowed to declare objects of this class. However, why the dog d is also incorrect? (given that the class dog is not abstract and so I can declare dog objects)

Thanks in advance!!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
PadK
  • 117
  • 1
  • 8

2 Answers2

1

The derived class Dog is also an abstract class because the pure virtual function show is not overridden. So the class Dog has the same pure virtual function.

Take into account that if you need the polymorphism then you have to declare the destructor of the base class as virtual.

At least you can write

class animal {
  public:
    virtual ~animal() = default;
    virtual void show()=0;
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Note that having a virtual destructor is not *required* but *highly recommended* in the example given. You don't need a virtual destructor unless you are planning on destroying derived objects by calling `delete` on base class pointers, in which case virtual dispatch is needed to make sure all derived destructors are called. That is not the case in this example. – Remy Lebeau Dec 19 '19 at 22:34
0

The important concept here that you are missing is that your abstract class, animal, has what is called a pure virtual function, which in your case, is

virtual void show()=0;

Normally, overriding a virtual function is optional. In your case, because you have declared your virtual function as pure by adding =0 to the end, the C++ compiler requires you to override show() in all classes that inherit from animal, such as dog.

To make your dog class non-abstract and compliant with your animal interface, add a function definition for show() in dog, so that the compiler can successfully link its parent's pure virtual function. That would look something like this:

class dog : public animal {
 inline void show()
    { //something here
      return;
    };
  int weight;
};

alteredinstance
  • 587
  • 3
  • 17
  • we don't normally use the `inline` keyword when the function is defined within the class definition. – JDługosz Dec 19 '19 at 19:13
  • Is there another way to make the function `inline`d when the definition is in the class definition? I guess I don't follow – alteredinstance Dec 19 '19 at 19:21
  • 2
    @alteredinstance -- a function that's defined inside the class definition is inline. That's why you don't need to say it. – Pete Becker Dec 19 '19 at 19:36