
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Virtual Functions in Derived Classes in C++
Virtual Functions in Derived Classes
A virtual function is declared using the virtual keyword in the base class and becomes a member function of the base class overridden by the derived class.
It becomes virtual in every class which is derived from the base class. So, the keyword virtual is not necessary in the derived class while declaring redefined versions of the virtual base class function.
When we use a pointer or reference to the base class to refer to a derived class object, we can call its virtual function.
Syntax
Following is the syntax of the virtual function in derived class:
class Base{ public: virtual return_type functionName(){ .... } } class Derived : public Base{ public: return_type functionName(){ ... } }
Implement Virtual Function in Derived class
The following is the basic C++ example of the demonstration of the virtual function in the derived class:
#include<iostream> using namespace std; class Base { public: virtual void s() { cout << " In Base \n"; } }; class Derived: public Base { public: void s() { cout << "In Derived \n"; } }; int main(void) { Derived d; // An object of class Derived Base * b = &d; // A pointer of type Base* pointing to derived b -> s(); return 0; }
Following is the output of the above code:
In Derived
Adding Two Number Using Virtual Function in Derived Class
Following is another example of the virtual function in the derived class:
#include<iostream> using namespace std; class Base { int a = 10; int b = 20; public: virtual void s() { cout << " In Base \n"; int sum = a + b; cout << "sum of two number: " << sum; } }; class Derived: public Base { int a = 30; int b = 40; public: void s() { cout << "In Derived \n"; int sum = a + b; cout << "sum of two number: " << sum; } }; int main(void) { Derived d; // An object of class Derived Base * b = & d; // A pointer of type Base* pointing to derived b -> s(); return 0; }
Following is the output:
In Derived sum of two number: 70
Factorial of a Number Using Virtual Function in Derived Class
Here, in this example, we use the virtual function in base class override within the derived class and compute the factorial of a number:
#include <iostream> using namespace std; class Base { public: virtual int factorial(int n) { return 1; } }; class Derived: public Base { public: int factorial(int n) override { if (n <= 1) return 1; return n * factorial(n - 1); } }; int main() { Derived obj; int num = 5; cout << "Factorial of " << num << " is " << obj.factorial(num) << endl; return 0; }
Factorial of a number:
In Derived Factorial of 5 is 120