Virtual Functions:

A virtual function is a function which is defined in base class and redefined in derived class.
Virtual functions give us the ability of run time polymorphism.

Rules for Virtual Functions:

  • They can not be static.
  • Virtual function can be a friend function.
  • They can be accessed using pointers of base class.
  • They are alwaysdefined in main class and overridden in derived class.
  • Virtual constructor is not allowed but virtual destructor is allowed.
When we call a virtual function using the pointer to base class, the most derived version of that function will be executed. We have discussed its implementation in our previous tutorial.

Pure Virtual Functions:

Pure virtual function is the function declared in the parent class but the parent class does not have its definition / implementation. But all the child classes have their own implementation of that function.

class Parent{
    public:
    virtual void makeSound() = 0;
};

Abstract Class:

A class which has atleast one pure virtual function is called an abstract class. In the above code, the class named "Parent" is an abstract class.

Note: We can not make object of abstract class.



Abstraction:

Abstraction is the hiding of implementation details of an object and exposing only the relevant and essential details to the users.
For example, when you feel headache you take medicine. You only take medicine. You get well and you do not know what is happening inside your body after taking medicine. That hidden details are abstractive for you. In short, in abstraction, complex details are hidden behind simple methods.
If you do not understand the example do not sweat it it, just move.

virtualFunc.cpp
#include <iostream>
using namespace std;
//this is the abstract class
class Animals{
    public:
 		virtual void behavior() = 0;
};
 
class Lion : public Animals{
 	public:
 		void behavior(){
 			cout<<"Lion rules. \n";
		 }
};
 
class Donkey : public Animals{
 	public:
 		void behavior(){
 			cout<<"Donkey works hard. \n";
		 }
};
 
int main(){
 	Animals *animal1 = new Lion();
 	/*as animal1 is a pointer to animal
  class therefore we are using -> operator 
  instead of dot operator for accessing 
  the members*/

 	animal1->behavior();
 	
 	Animals *animal2 = new Donkey();
 	animal2->behavior();
    return 0;
}

Note: When we make a pointer to a class, we then access the data members using arrow. In this case, we can not use dot operator.