Sunday, 15 April 2012

Write about the functional overriding of the base class by the member function in the derived class. | C++

You'can customize a base class by redefining its members in the derived class. This process is called overriding. When you override a base class's member, you redefine the member, whether it is a data member or a method. For example, the animal class has a method named breathe that prints "Breathing...", but if you derive a class named fish from the animal class, you might think it more appropriate if that method were to print out "Bubbling../'. To override the base class's method, you simply need to redefine that method. Let's understand this concept with the help of the following code snippet:

#include <iostream.h>
#include <conio.h>
class animal
{
public:
void eat();
void sleep();
void breathe();
};
class fish : public animal
{
public:
void breathe();
};
void animal :: eat()
{
cout << "Eating..." <
}
void animal :: sleep()
{
cout << "Sleeping..." < }
void animal :: breathe()
{
cout << "Breathing..." < }
int main()
{
animal fish;
fish.breathe();
getch();
return 0;
}
Note:: that the overridden breathe method displays "Breathing". As you can see, the fish class's breathe method has overridden the base class's breathe method. In this way, you can still use a base class, even if a few methods or data members are inappropriate by redefining that particular method in a derived class.

No comments: