Virtual Functions

From WikiKantila

Jump to: navigation, search
/**
* Program to demonstrate difference between virtual functions & normal function
* Written by	:	Mohit Goel
* Guided by	:	Sudesh Kantila
* Dated		:	25th April 2008
* Last Modified :	25th April 2008
*/


#include <iostream>
using namespace std;

namespace secs
{
	class A
	{
		public:
			virtual void vprint()
			{
				cout<<"Virtual function of class A"<<endl;
		
			}
			void print()
			{
				cout<<"Normal function of class A"<<endl;
			}
	};
	
	class B: public A
	{
		public:
			virtual void vprint()
			{
				cout<<"Virtual function of class B"<<endl;
			}
			void print()
			{
				cout<<"Normal function of class B"<<endl;
			}
	};
}

//main function
using namespace secs;
int main()
{
	A *p,*q;
	
	p=new A();
	q=new B();
	
	//call to normal functions always bind to the functions of the class of the pointer itself
	p->print();	//binds to print() of class A because p is a pointer of class A
	q->print();	//binds to print() of class A because p is a pointer of class A

	//call to virtual functions bind to the functions of the object being pointed at that time
	p->vprint();	//binds to vprint() of class A because p is pointing to an obj of class A
	q->vprint();	//binds to vprint() of class B because q is pointing to an obj of class B
	
	return 0;
}

Go back to C++ Programs

Personal tools