cogp
cogp

Reputation: 5

Calling virtual function from virtual destructor error C++

I get unresolved external symbol when calling virtual function from virtual destructor.

#include <iostream>

class Animal {
public:
  virtual void Sound() = 0;

  virtual ~Animal() {
    this->Sound();
  }
};

class Dog : public Animal {
public:
  void Sound() override {
    printf("Woof!\n");
  }
};

class Cat : public Animal {
public:
  void Sound() override {
    printf("Meow!\n");
  }
};

int main() {
  Animal* dog = new Dog();
  Animal* cat = new Cat();

  dog->Sound();
  cat->Sound();

  delete dog;
  delete cat;

  system("pause");
  return 0;
}

Why? Also I tried edit destructor to this:

  void Action() {
    this->Sound();
  }

  virtual ~Animal() {
    this->Action();
  }

Now code is compiling, but in destructor I get pure virtual function call. How can I solve it?

Upvotes: 0

Views: 130

Answers (1)

Jasper Kent
Jasper Kent

Reputation: 3676

By the time you call the Animal destructor, the derived class (Dog/Cat) has already had its destructor called, thus it is invalid. Calling Dog::sound() would risk accessing destroyed data.

Thus the destructor call is not allowed to access derived class methods. It tries to access Animal::sound(), but it's pure virtual - hence the error.

Upvotes: 2

Related Questions