Virtual functions
#include <iostream>
class Animal {
public:
virtual void makeSound() {
std::cout << "The animal makes a sound" << std::endl;
}
virtual ~Animal() {
std::cout << "Animal destructor called" << std::endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
std::cout << "The dog barks: Woof!" << std::endl;
}
~Dog() override {
std::cout << "Dog destructor called" << std::endl;
}
};
class Cat : public Animal {
public:
void makeSound() override {
std::cout << "The cat meows: Meow!" << std::endl;
}
~Cat() override {
std::cout << "Cat destructor called" << std::endl;
}
};
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animal1->makeSound(); // Outputs: The dog barks: Woof!
animal2->makeSound(); // Outputs: The cat meows: Meow!
delete animal1; // Calls Dog destructor, then Animal destructor
delete animal2; // Calls Cat destructor, then Animal destructor
return 0;
}Last updated