Virtual Functions in C++
Once again we are into a completely new topic with terminology which will be new to you. If you are new to object oriented programming, you should follow along in this tutorial very carefully because every attempt has been made to define every detail of this new and somewhat intimidating topic.
One term which must be defined is polymorphism, a rather large word that simply means similar when used in the context of object oriented programming. Objects are polymorphic if they have some similarities but are still somewhat different. We will see how it is used in the context of object oriented programming as we proceed.
We have already studied operator overloading and function overloading in this tutorial, and they are a subtle form of polymorphism since in both cases, a single entity is used to refer to two or more things. The use of virtual functions can be a great aid in programming some kinds of projects as you will see in these two chapters.
So what is a Virtual Function?
A Virtual function is a function whic is declared in base class using the keyword virtual. We write the body of virtual function in the derived classes. Its purpose is to tell the compiler that what function we would like to call on the basis of the object of derived class. C++ determines which function to call at run time on the type of object pointer to.
Declaration of a virtual function
class BaseClass{
public:
virtual void who(void)
{
cout << "Base\n";
}
};
class Derived1 : public BaseClass
{
public:
void who (void)
{
cout << "Derived Class 1 \n";
}
};
class Derived2 : public BaseClass
{
public:
void who (void)
{
cout << "Derived Class 2\n";
}
};
int main(void)
{
BaseClass b;
BaseClass *bp;
Derived1 d1;
Derived2 d2;
bp = &b;
bp ->who(); //Executes the base class who function
bp = &d1;
bp ->who(); //Executes the Derived1 class who function
bp = &d2;
bp ->who(); //Executes the Derived2 class who function
}
//Out put
//Base
//Derived Class 1
//Derived Class 2
Here in this example who(); function is called on the basis of the object. So if the object is of the base class then who(); function called is defined in base class.
Pages: [Page - 1] [Page - 2] [Page - 3] [Page - 4] [Page - 5] [Page - 6]
Tags: C++ Programming, Derived Class, Functions, Inheritance, Virtual, Virtual Function
Like What you See?
Become one of the regulars by subscribing! You'll be the first to know when we add more great posts just like this. Join up by either RSS Feeds or Email Updates today!
There are 15 Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.



































A derived class has an method which overrides its base class’s virtual method and where in the derived class overridden method has some code that accesses derived class’s variables.
In this scenario, if a base class pointer is assigned derived calss reference(ie.. late binding) and the overridden method is called using base class pointer then only the base class implementation of the method is called but not the derived class method implemention.
Virtual Method example –
#include "stdafx.h" #include <iostream> using namespace std; class Base { public: Base(){ cout<<"Constructor: Base"<<endl;} virtual ~Base(){ cout<<"Destructor : Base"<<endl;} virtual void GetName() {cout<<"Base class GetName called.";} }; class Derived: public Base { //Doing a lot of jobs by extending the functionality public: Derived(){ cout<<"Constructor: Derived"<<endl;} ~Derived(){ cout<<"Destructor : Derived"<<endl;} void GetName(); }; void Derived::GetName() { cout<<"Derived class GetName called."; } void main() { Base *pBase = NULL; Base objBase; Derived objDerived; pBase = &objBase; pBase->GetName(); getchar(); }Simple and great explanation!
Good one.
Keep it up
Simple and clear explanation. Good for beginners.
Nicely explained with simple examples. It really helped me.
it is very easy and more useful for me
u can easily understanding other by this prog:-
class B; class A; { protected: int ax; public: virtual getdata() { cout<<"enter the value of ax:"; cin>>ax; } virtual showdata() { cout<<"the value of ax is :"<<ax; } }; class B:public A { protected: int bx; public: getdata() { cout<<"enter the value of bx:"; cin>>bx; } showdata() { cout<<"the value of bx is :"<<bx; } }; main() { B*ptr; ptr=new B; ptr->getdata(); ptr->showdata(); }Assumption: machine is 32-bit .
Here I am going to explain How Virtual table, Virtual pointer for Virtual functions are internally working.
First we have understand memory layout.
Example 1: How the class’s memory layout
class Test { public: int data1; int data2; int fun1(); }; int main() { Test obj; cout << "obj's Size = " << sizeof(obj) << endl; cout << "obj 's Address = " << &obj << endl; return 0; }Output:
Sobj’s Size = 8
obj ’s Address = 0012FF7C
Note: Any Plane member function does not take any memory.
Example 2: Memory Layout of Derived class
class Test { public: int a; int b; }; class dTest : public Test { public: int c; }; int main() { Test obj1; cout << "obj1's Size = " << sizeof(obj1) << endl; cout << "obj1's Address = " << &obj1 << endl; dTest obj2; cout << "obj2's Size = "<< sizeof(obj2) << endl; cout << "obj2's Address = "<< &obj2 << endl; return 0; }OUTPUT:
obj1’s Size = 8
obj1’s Address = 0012FF78
obj2’s Size = 12
obj2’s Address = 0012FF6C
Example 3: Memory layout If we have one virtual function.
class Test { public: int data; virtual void fun1() { cout << "Test::fun1" << endl; } }; int main() { Test obj; cout << "obj's Size = " << sizeof(obj) << endl; cout << "obj's Address = " << &obj << endl; return 0; }OUTPUT:
obj’s Size = 8
obj’s Address = 0012FF7C
Note: Adding one virtual function in a class takes 4 Byte extra.
Example 4: More than one Virtual function
class Test { public: int data; virtual void fun1() { cout << "Test::fun1" << endl; } virtual void fun2() { cout << "Test::fun2" << endl; } virtual void fun3() { cout << "Test::fun3" << endl; } virtual void fun4() { cout << "Test::fun4" << endl; } }; int main() { Test obj; cout << "obj's Size = " << sizeof(obj) << endl; cout << "obj's Address = " << &obj << endl; return 0; }OUTPUT:
obj’s Size = 8
obj’s Address = 0012FF7C
Note: Adding more virtual functions in a class, no extra size taking i.e. Only one machine size taking(i.e. 4 byte)
Example 5:
class Test { public: int a; int b; Test(int temp1 = 0, int temp2 = 0) { a=temp1 ; b=temp2 ; } int getA() { return a; } int getB() { return b; } virtual ~Test(); }; int main() { Test obj(5, 10); // Changing a and b int* pInt = (int*)&obj; *(pInt+0) = 100; *(pInt+1) = 200; cout << "a = " << obj.getA() << endl; cout << "b = " << obj.getB() << endl; return 0; }OUTPUT:
a = 200
b = 10
If we Change the code as then
// Changing a and b
int* pInt = (int*)&obj;
*(pInt+1) = 100; // In place of 0
*(pInt+2) = 200; // In place of 1
OUTPUT:
a = 100
b = 200
Note: Who sits 1st place of Class : Answer is VPTR
VPTR – 1st placed in class and rest sits after it.
Example 6:
class Test { virtual void fun1() { cout << "Test::fun1" << endl; } }; int main() { Test obj; cout << "VPTR's Address " << (int*)(&obj+0) << endl; cout << "VPTR's Value " << (int*)*(int*)(&obj+0) << endl; return 0; }OUTPUT:
VPTR’s Address 0012FF7C
VPTR’s Value 0046C060
NOTE: This VPTR’s value is a address of Virtual table. Lets see in next Example.
Example 7:
#include <iostream> using namespace std; class Test { virtual void fun1() { cout << "Test::fun1" << endl; } }; typedef void (*Fun)(void); int main() { Test obj; cout << "VPTR's Address " << (int*)(&obj+0) << endl; cout << " VIRTUAL TABLE 's Address " << (int*)*(int*)(&obj+0) << endl; // Value of VPTR cout << "Value at first entry of VIRTUAL TABLE " << (int*)*(int*)*(int*)(&obj+0) << endl; Fun pFun = (Fun)*(int*)*(int*)(&obj+0); // calling Virtual function pFun(); return 0; }OUTPUT:
VPTR’s Address 0012FF7C
VIRTUAL TABLE ’s Address 0046C0EC
Value at first entry of VIRTUAL TABLE 0040100A
Test: fun1
Example 8:
class Test { virtual void fun1() { cout << "Test::fun1" << endl; } virtual void func1() { cout << "Test::func1" << endl; } }; int main() { Test obj; cout << "VPTR's Address " << (int*)(&obj+0) << endl; cout << "VIRTUAL TABLE 's Address"<< (int*)*(int*)(&obj+0) << endl; // Calling Virtual table functions cout << "Value at 1st entry of VTable " << (int*)*((int*)*(int*)(&obj+0)+0) << endl; cout << "Value at 2nd entry of VTable " << (int*)*((int*)*(int*)(&obj+0)+1) << endl; return 0; }OUTPUT:
VPTR’s Address 0012FF7C
VIRTUAL TABLE ’s Address 0046C0EC
Value at first entry of VIRTUAL TABLE 0040100A
Value at 2nd entry of VIRTUAL TABLE 004012
Example :9
class Test { virtual void fun1() { cout << "Test::fun1" << endl; } virtual void func1() { cout << "Test::func1" << endl; } }; typedef void(*Fun)(void); int main() { Test obj; Fun pFun = NULL; // calling 1st virtual function pFun = (Fun)*((int*)*(int*)(&obj+0)+0); pFun(); // calling 2nd virtual function pFun = (Fun)*((int*)*(int*)(&obj+0)+1); pFun(); return 0; }OUTPUT:
Test::fun1
Test::func1
Example 10: multiple Inheritance
class Base1 { public: virtual void fun(); }; class Base2 { public: virtual void fun(); }; class Base3 { public: virtual void fun(); }; class Derive : public Base1, public Base2, public Base3 { }; int main() { Derive obj; cout << "Derive's Size = " << sizeof(obj) << endl; return 0; }OUTPUT:
Derive’s Size = 12
Example 11: Calling Virtual Functions in case of Multiple Inheritance
class Base1 { virtual void fun1() { cout << "Base1::fun1()" << endl; } virtual void func1() { cout << "Base1::func1()" << endl; } }; class Base2 { virtual void fun1() { cout << "Base2::fun1()" << endl; } virtual void func1() { cout << "Base2::func1()" << endl; } }; class Base3 { virtual void fun1() { cout << "Base3::fun1()" << endl; } virtual void func1() { cout << "Base3::func1()" << endl; } }; class Derive : public Base1, public Base2, public Base3 { public: virtual void Fn() { cout << "Derive::Fn" << endl; } virtual void Fnc() { cout << "Derive::Fnc" << endl; } }; typedef void(*Fun)(void); int main() { Derive obj; Fun pFun = NULL; // calling 1st virtual function of Base1 pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+0); pFun(); // calling 2nd virtual function of Base1 pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+1); pFun(); // calling 1st virtual function of Base2 pFun = (Fun)*((int*)*(int*)((int*)&obj+1)+0); pFun(); // calling 2nd virtual function of Base2 pFun = (Fun)*((int*)*(int*)((int*)&obj+1)+1); pFun(); // calling 1st virtual function of Base3 pFun = (Fun)*((int*)*(int*)((int*)&obj+2)+0); pFun(); // calling 2nd virtual function of Base3 pFun = (Fun)*((int*)*(int*)((int*)&obj+2)+1); pFun(); // calling 1st virtual function of Drive pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+2); pFun(); // calling 2nd virtual function of Drive pFun = (Fun)*((int*)*(int*)((int*)&obj+0)+3); pFun(); return 0; }OUTPUT:
Base1::fun
Base1::func
Base2::fun
Base2::func
Base3::fun
Base3::func
Drive::Fn
Drive::Fnc
By
Asadullah Ansari
Hi! It’s Very Good Fundamental Example.
How To Use 3 tier Architecture in C#
Sent Me At=savaliyabhavesh@rediff.com
class Test { public: int a; int b; Test(int temp1 = 0, int temp2 = 0) { a=temp1 ; b=temp2 ; } int getA(){ return a; } int getB(){ return b; } virtual ~Test(); }; int main() { Test obj(5, 10);// Changing a and b int* pInt = (int*)&obj; *(pInt+0) = 100; *(pInt+1) = 200; cout < < "a = " << obj.getA() << endl; cout << "b = " << obj.getB() << endl; return 0; }soalannya kenapa program di atas tidak dapat di jalan kan....harap balas....email..zakrie3@Yahoo.com
kenape kebanyakan program tidak dapat d jalankan..?
Hi, I am a newbie in C++.
Can somebody tell me why constructors can never be virtual?
Thanks in advance.
Declaring something virtual in C++ means that it can be overridden by a sub-class of the current base class. But logically we will never need to override the constructors in the derived class. So if you declare virtual constructors it’s of no use.
Thanks a lot Saqib!!!