简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM