C++ Interview

Pure Virtual Functions and Abstract Classes in C++

A class is an abstract class if it will contain at least one virtual function. We can't create the object of the Abstract class because if we create the object of the abstract then we can also call the function of virtual that is virtual function has no definition. To stop the calling of virtual function c++ can create rule that is we cannot create an object of the abstract class.

Pure Virtual Function:-  It is a function in which declares a function in the class, but we can not define that function. A virtual function is declared by assigning 0.

Example: virtual int Name()=0;

Why we use an abstract class?

Sometimes in big projects, we just declare the function in the Base class or the parent class. When we require these function then we can inherit the Base class and override the function according to requirement.

For example:- We create the software for College so we can’t create the different functions for Professor and different functions for Student information. If we create a different function for different persons of the college that make the project complex and not efficient. So we create a general class Person that has function Name, Date of Birth, Roll Number, Address. So function these override in their child class according to requirement.

Untitled Diagram

 

Abstract Class:-

  • A class is an abstract class if it will contain at least one virtual function.
  • We can’t create the object of the Abstract class because if we create the object of the abstract then we can also call the function of virtual that is virtual function has no definition. To stop the calling of virtual function c++ can create rule that is we cannot create an object of the abstract class.
  • To call the pure virtual function first we override that function and give definition to that function.

For Example :

#include <iostream>

using namespace std;

class person
{
    public:
    // declaration of pure virtual function by assigning 0
    virtual int Name()=0;
};

class student : public person
{
    public:
    int Name()
    {
        cout<<"Student Name";
    }
};

int main()
{
   student st;
   st.Name();
   

    return 0;
}
 Output: Student Name

 

Leave a Reply

%d bloggers like this: