- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Inline virtual function in C++
- Difference between a virtual function and a pure virtual function in C++
- What happens when a virtual function is called inside a non-virtual function in C++
- Default arguments and virtual function in C++
- Difference Between Virtual and Pure Virtual Function
- How to call a virtual function inside constructors in C++?
- C++ interview questions on virtual function and abstract class
- Why is a C++ pure virtual function initialized by 0?
- Virtual Destructor in C++
- Virtual Constructor in C++
- Pure virtual destructor in C++
- Virtual Copy Constructor in C++
- Virtual base class in C++
- Virtual destruction using shared_ptr in C++
- What are virtual functions in C#?

Advertisements