DEV Community

Cover image for Virtual Function and Abstract Class in C++ - Explained in Simple Words
Aliza Kanwal
Aliza Kanwal

Posted on

Virtual Function and Abstract Class in C++ - Explained in Simple Words

What is Virtual Function and Abstract Class in C++?

Virtual Function and Abstract Class are used when we want child class to change the behavior of parent class. This is the heart of Runtime Polymorphism.

What is Virtual Function?

Virtual Function is a function in parent class which we expect child class to override later.

We write virtual keyword before it.

Example of Virtual Function:

include

using namespace std;

class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};

class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks" << endl;
}
};

class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};

int main() {
Animal* a;
Dog d;
Cat c;
a = &d;
a->sound();
a = &c;
a->sound();
return 0;
}

Output:
Dog barks
Cat meows

Here same pointer a calls different functions. This is possible only because function is virtual.

What is Abstract Class?

Abstract Class is a class which has at least one Pure Virtual Function.

Pure Virtual Function means function with no body, only = 0.

Example: virtual void sound() = 0;

We cannot create object of Abstract Class. We can only use it as parent.

Example of Abstract Class:

include

using namespace std;

class Shape {
public:
virtual void draw() = 0; // Pure Virtual Function
};

class Circle : public Shape {
public:
void draw() override {
cout << "Drawing Circle" << endl;
}
};

int main() {
Circle c;
c.draw();
return 0;
}

Output:
Drawing Circle

Here Shape is Abstract Class because it has pure virtual function. Circle must implement draw(), otherwise Circle will also become abstract.

Virtual vs Abstract - Easy Difference:

Virtual Function: Has body, child may override. We can create object of that class.

Abstract Class: Has at least one pure virtual function with no body. We cannot create object. Child must override.

Conclusion:
Virtual Function gives freedom to child to change behavior. Abstract Class gives rule to child that you must implement this function. Both are used to make clean and flexible code.

I have tested this code myself and it works perfectly.

Top comments (0)