In this article, we will discuss the behavior of Virtual Function in the derived class and derived class from the Abstract Base Class in C++ .
Consider the following program:
C++
#include <bits/stdc++.h>
using namespace std;
class Base {
public:
virtual void print()
{
cout << "Inside Base" << endl;
}
};
class Derived : public Base {
};
int main()
{
Base* b2 = new Derived();
b2->print();
return 0;
}
Explanation: When a pointer of the Base Class is declared pointing to an object of the Derived Class , then only declare the function as virtual in the base when it is needed to override it in the derived class. If the function is declared as a virtual in the Base Class, then it is not recommended to override it in the derived class, it will still call the virtual function and execute it.
The virtual keyword only works when going for runtime polymorphism and overriding the function of the base class in the derived class. If a virtual keyword is used, and it is not recommended to override that function in the derived class, then the virtual keyword is of no use. This property doesn’t hold true for the Abstract Base class because there is no function body in the Base class as well. Below is the program to illustrate the same:
Program 1:
C++
#include <bits/stdc++.h>
using namespace std;
class Base {
public:
virtual void print() = 0;
};
class Derived : public Base {
void print()
{
cout << "Inside Derived"
<< endl;
}
};
int main()
{
Base* b2 = new Derived();
b2->print();
return 0;
}
Program 2:
C++
#include <bits/stdc++.h>
using namespace std;
class Base {
public:
virtual void print() = 0;
};
class Derived : public Base {
};
int main()
{
Base* b2 = new Derived();
b2->print();
return 0;
}
Output:
Explanation: If the above two programs are compared, when the function is overridden of the abstract class, then the virtual keyword is working the way it has been intended to work. But in the above program, the function wasn’t overridden inside the Base Class, and also the function was not defined in the Base Class, result in the Compilation Error .
Learn to code easily with our course
Coding for Everyone . This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
06 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...