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

Virtual-Functions

cpp

Uploaded by

kumarrishi5826
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Virtual-Functions

cpp

Uploaded by

kumarrishi5826
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Virtual Functions

Example
A virtual function is a member function in the base
class that we expect to redefine in derived classes.
Basically, a virtual function is used in the base class
in order to ensure that the function is overridden.
This especially applies to cases where a pointer of
base class points to an object of a derived class.
This provides flexibility and code reusability in object-
oriented programming.

b y RISHI KUMAR
(1MV23IS087)
D e c l a ra t i o n o f Virtual Functions

class Base
{
public:
Virtual Keyword virtual void print()
{
A virtual function is declared using the 'virtual' // code
keyword in the base class. This function can be }
};
overridden in derived classes.
class Derived : public Base
{
public:
SYNTAX : void print()
{
virtual return_type Function_name() // code
{ }
//code };
}
int main()
Example {
base* bptr; //pointer object of base class
#include <iostream> derived d; //object of derived class
using namespace std; bptr = &d; // pointer of base class points to an
object of a derived class.
class base {
public: // Virtual function, binded at runtime
virtual void print() { cout << "print base class\n"; } bptr->print();

void show() { cout << "show base class\n"; } // Non-virtual function, binded at compile time
}; bptr->show();

class derived : public base return 0;


{ }
public:
void print() { cout << "print derived class\n"; } Output :
print derived class
void show() { cout << "show derived class\n"; } show base class
};
B e n e f i t s of
Virtual Functions

Flexibility C o d e Reuse
Polymorphism with Virtual functions allow
virtual functions enables code reuse by providing
writing more flexible and a common interface in
extensible code, as new the base class, with
derived classes can be specifi c implementations
added without in derived classes.
modifying existing code.

You might also like