Virtual Function: Virtual functions are used to achieve runtime polymorphism in C++. They allow derived classes to override the base class’s implementation of a function, providing different behavior based on the dynamic type of the object.
Pure virtual Function: Pure virtual functions are virtual functions that have no implementation in the base class. They are declared by assigning the value 0 to the function’s return type.
Difference Between virtual function and pure virtual function
Below is the Difference Between virtual function and pure virtual function:
Virtual Function | Pure virtual Function |
---|---|
it is a function of the base class which can be redefined by derived class | it is a function of the base class that should be redefined by the derived class otherwise, the derived class also becomes abstract |
The class which contains virtual functions is not abstract | it is a function of the base class which can be redefined by the derived class |
Declared using virtual keyword | declared using virtual keyword and equal to zero |
function is defined in base class | function is not defined in base class |
Syntax: Virtual Function_name(arg list) { //code } | Syntax: Virtual Function_name(arg list)=0; |
virtual Function Program:
#include <iostream>
using namespace std;
class Animal {
public:
virtual void whatDoIEat()
{
cout << "I eat food." << std::endl;
}
virtual ~Animal() {}
};
class Dog : public Animal
{
public:
void whatDoIEat()
{
cout << "I eat dog food." << std::endl;
}
};
class Cat : public Animal
{
public:
void whatDoIEat(){
std::cout << "I eat cat food." << std::endl;
}
};
class Cow : public Animal {
public:
void whatDoIEat()
{
std::cout << "I eat grass." << std::endl;
}
};
int main()
{
Animal *a;
Dog d;
Cat c;
a=&d;
a->whatDoIEat();
a=&c;
a->whatDoIEat();
return 0;
}
Pure Virtual Function program:
#include <iostream>
using namespace std;
class Animal {
public:
// Pure virtual function
virtual void whatDoIEat() = 0;
// Virtual destructor
virtual ~Animal() {}
};
class Dog : public Animal {
public:
void whatDoIEat() override {
cout << "I eat dog food." << std::endl;
}
};
class Cat : public Animal {
public:
void whatDoIEat() override {
cout << "I eat cat food." << std::endl;
}
};
class Cow : public Animal {
public:
void whatDoIEat() override {
cout << "I eat grass." << std::endl;
}
};
int main() {
Animal* a; // Pointer to Animal
Dog d; // Create a Dog object
Cat c; // Create a Cat object
// Point to Dog and call whatDoIEat
a = &d;
a->whatDoIEat();
// Point to Cat and call whatDoIEat
a = &c;
a->whatDoIEat();
return 0;
}