Sub topic 2
Overriding Virtual Functions
Overriding a virtual function
An override is a function in a derived class that replaces a base class’s virtual function. When a call uses a base reference to a derived object, the override can run instead.
Write override after the function declaration. It tells the compiler to check that the function really overrides a base function. The parameter list and const must match. In the example below, both functions also return void.
You can add final after override to stop further derived classes from overriding that function.
Object slicing and references
Object slicing happens when a derived object is copied into a base object. The new object contains only the base-class part. Passing by value makes such a copy.
A polymorphic reference is a base-class reference that refers to a derived object. It avoids slicing and allows virtual calls to reach the override.
Run this example:
#include <iostream>
#include <memory>
class Animal {
public:
virtual void speak() const {
std::cout << "Animal\n";
}
virtual ~Animal() = default;
};
class Dog : public Animal {
public:
void speak() const override {
std::cout << "Dog\n";
}
};
void speak_copy(Animal animal) {
animal.speak();
}
void speak_ref(const Animal& animal) {
animal.speak();
}
int main() {
Dog dog;
speak_ref(dog); // Dog
speak_copy(dog); // Animal
std::unique_ptr<Animal> pet = std::make_unique<Dog>();
pet->speak(); // Dog
}speak_ref refers to the original Dog, so it prints Dog. speak_copy receives an Animal copy, so it prints Animal.
Virtual destructors and ownership
A destructor is a function that runs when an object is destroyed. A virtual destructor lets C++ destroy the complete derived object when it is deleted through a base pointer.
In the example, pet is a std::unique_ptr<Animal>, a smart pointer that owns its object and deletes it automatically. The object it owns is a Dog. The virtual Animal destructor makes that deletion safe.
Exercise
In the example, why does speak_copy(dog) print Animal rather than Dog?
Show answer
Passing by value creates an Animal copy. The Dog part is sliced off, so the call uses Animal::speak.