0% found this document useful (0 votes)
6 views

7. Virtual Functions

The document explains the concept of virtual functions in C++, which are member functions defined in a base class that can be overridden in derived classes. An example is provided, demonstrating how a base class pointer can call the overridden function in the derived class while a non-virtual function calls the base class version. The code illustrates the difference between virtual and non-virtual function calls.

Uploaded by

kranokmusic
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

7. Virtual Functions

The document explains the concept of virtual functions in C++, which are member functions defined in a base class that can be overridden in derived classes. An example is provided, demonstrating how a base class pointer can call the overridden function in the derived class while a non-virtual function calls the base class version. The code illustrates the difference between virtual and non-virtual function calls.

Uploaded by

kranokmusic
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Virtual Function 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();
}

You might also like