Overriding Method
Method overriding is the ability of the inherited class rewriting the virtual method of the base class. With overriding, the method in the inherited class has the identical signature to the method in the base class. The inherited class can selectively use some base class methods as they are, and override others.
In the following example, the speak method of the Pet class will be overridden in each inherited class.
#include <iostream>
#include <string>
using namespace std;
class Pet
{
public:
// Constructors, Destructors
Pet () : weight(1), food("Pet Chow") {}
Pet(int w) : weight(w), food("Pet Chow") {}
Pet(int w, string f) : weight(w), food(f) {}
~Pet() {}
//Accessors
void setWeight(int w) {weight = w;}
int getWeight() {return weight;}
void setfood(string f) {food = f;}
string getFood() {return food;}
//General methods
void eat();
virtual void speak();
protected:
int weight;
string food;
};
void Pet::eat()
{
cout << "Eating " << food << endl;
}
void Pet::speak()
{
cout << "Growl" << endl;
}
class Rat: public Pet
{
public:
Rat() {}
Rat(int w) : Pet(w) {}
Rat(int w, string f) : Pet(w,f) {}
~Rat() {}
//Other methods
void sicken() {cout << "Speading Plague" << endl;}
void speak();
};
void Rat::speak()
{
cout << "Rat noise" << endl;
}
class Cat: public Pet
{
public:
Cat() : numberToes(5) {}
Cat(int w) : Pet(w), numberToes(5) {}
Cat(int w, string f) : Pet(w,f), numberToes(5) {}
Cat(int w, string f, int toes) : Pet(w,f), numberToes(toes) {}
~Cat() {}
//Other accessors
void setNumberToes(int toes) {numberToes = toes;}
int getNumberToes() {return numberToes;}
//Other methods
void speak();
private:
int numberToes;
};
void Cat::speak()
{
cout << "Meow" << endl;
}
int main()
{
Pet aPet;
Rat aRat;
Cat aCat;
aPet.speak();
aRat.speak();
aCat.speak();
return 0;
}
Output:
Crowl
Rat noise
Meow
Notice that each inherited class implements and uses its own speak method. The base class speak method is overridden.
Also, remember that the return type and signature of the inherited class method must match the base class method exactly to override.