Tuesday, 17 April 2012

Write about pure virtual member function. | C++

You can leave a base class method unimplemented if you make it a pure virtual method. A class's member function declaration includes an equal sign followed by a zero (=0).
This means that the base class is an abstract base class and the class designer intends the class to be used only as a base class. The base class may or may not provide a function body for the pure virtual function. In either case, a program that uses this class may not directly declare any objects of an abstract base class. If the program declares an object of a
class directly or indirectly derived from the abstract base class, the pure virtual function must be overridden explicitly.
Let's take an example. There is an animal class and you need to make the breathe function in the animal class as a pure virtual function:

#include <iostream.h>
using namespace std;
class animal
{
public:
virtual void breathe () = 0 // 0 means it is "Pure Virtual"
};

Now, the animal class is an abstract class and you cannot create objects of this class. You can only use it as a base class. To create a non-abstract derived class from this class, you must override the breathe function, as follows:
#include <iostream.h>
#include <conio.h>
class animal
{
public:
virtual void breathe () = 0;
};
class fish: public animal
{
public:
void breathe ();
};
void fish::breathe()
{
cout << "Building_" << endl; } 

int main() 

fish bigfish; bigfish.breathe(); 
getch(); 
return 0; 
}
 In the preceding code snippet, the animal and fish classes each have a different version of a function named breathe. That means that pointer->breathe calls animal::breathe when pointer points to an animal object, but it calls fish::breathe when pointer points to a fish object.

No comments: