Virtual Functions


Introduction

           A virtual function is a member function that is declared within a base class and redefined by a derived class. To create a virtual function, precede the function's declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited,the derived class redefines the virtual function to fit its own needs. In essence, virtual functions implement the "one interface, multiple methods" philosophy that underlies polymorphism. The virtual function within the base class defines the form of the interface to that function. Each redefinition of the virtual function by a derived class plements its operation as it relates specifically to the derived class. That is, the redefinition
creates a specific method.

// Virtual.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class base
{
public:
void virtual vFun()
{
cout<< "Base VFun" <<endl;
}
};
class D1 : public base
{
public:
 void virtual vD1fun()
 {
 cout << "D1 Function()"<<endl;
 }
 void vFun()
 {
 cout << "D1 vFun"<<endl;
 }
};
class D2 : public D1
{
public:
 void vD1fun()
 {
 cout << "D2 Function()"<<endl;
 }
  void vFun()
 {
 cout << "D2 vFun"<<endl;
 }
};
void vRefFun(base &b)
{
b.vFun();
}
int _tmain(int argc, _TCHAR* argv[])
{
base *b_ptr , b_obj;

cout<< sizeof(base) <<endl;
cout<< sizeof(D1) <<endl;
cout<< sizeof(D2) <<endl;

b_ptr = new D1();
b_ptr->vFun();

D1 *d_ptr , d_obj;
d_ptr = static_cast<D1 *> (new base()) ; // No Safe becasue b_ptr can only hold base values and not derived
d_ptr->vFun();


D1 *D1_ptr , D1_obj;
D2 *D2_ptr , D2_obj;

D1_ptr = &D2_obj;
D1_ptr->vD1fun();
D1_ptr->vFun();

D2_ptr = static_cast<D2*>(&D1_obj);
D2_ptr->vD1fun();
D2_ptr->vFun();

vRefFun(b_obj);
vRefFun(D1_obj);
vRefFun(D2_obj);

D2_ptr = dynamic_cast<D2*>(&D1_obj);
D2_ptr->vD1fun();
D2_ptr->vFun();
return 0;
}



Comments

Popular posts from this blog

Smart Pointers in C++ and How to Use Them

Operator Overloading in C++

How would you read in a string of unknown length without risking buffer overflow