When a virtual function is declared in a ancestor base class and is overridden by a derived class, calling the base class's virtual method instead of the direct parent's method is considered a bad practice. This is because the ancestor class may have implemented the virtual method differently, leading to unintended behavior.
If this issue remains in the code, it can cause unexpected behavior at runtime, as the intended behavior of the overridden method may not be executed.
To fix this issue, replace the call to the ancestor's virtual method with a call to the direct parent's method.
#include <iostream>
class Animal {
public:
virtual void speak() {
std::cout << "Animal speaks!" << std::endl;
}
};
class Dog : public Animal {
public:
void speak() override {
std::cout << "Woof!" << std::endl;
}
};
class Labrador : public Dog {
public:
void speak() override {
// bad practice - calling the ancestor's virtual method instead of direct parent's method
Animal::speak();
}
};
int main() {
Labrador labrador;
labrador.speak(); // outputs "Animal speaks!" instead of "Woof!"
return 0;
}
In the above example, the Labrador
class calls Animal::speak()
instead of Dog::speak()
.
To fix this issue, we should call Dog::speak()
instead of Animal::speak()
.
#include <iostream>
class Animal {
public:
virtual void speak() {
std::cout << "Animal speaks!" << std::endl;
}
};
class Dog : public Animal {
public:
void speak() override {
std::cout << "Woof!" << std::endl;
}
};
class Labrador : public Dog {
public:
void speak() override {
// recommended - calling the direct parent's method
Dog::speak();
}
};
int main() {
Labrador labrador;
labrador.speak(); // outputs "Woof!" as expected!
return 0;
}