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

  1. They can not be static.
  2. Virtual function can be a friend function.
  3. They can be accessed using pointers of base class.
  4. They are always defined in main class and overridden in derived class.
  5. 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.

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, just move.

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.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min