
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 Function in C++
In this tutorial, we will be discussing a program to understand virtual functions in C++.
Virtual function is the member function defined in the base class and can further be defined in the child class as well. While calling the derived class, the overwritten function will be called.
Example
#include <iostream> using namespace std; class base { public: virtual void print(){ cout << "print base class" << endl; } void show(){ cout << "show base class" << endl; } }; class derived : public base { public: void print(){ cout << "print derived class" << endl; } void show(){ cout << "show derived class" << endl; } }; int main(){ base* bptr; derived d; bptr = &d; //calling virtual function bptr->print(); //calling non-virtual function bptr->show(); }
Output
print derived class show base class
Advertisements