Friday, 27 March 2009

Example of Virtual Functions

The following is a simple example of Virtual functions. There is a Shape class which is the base class and three other classes are derived from the Shape class. The Circumference method in the base class is 'pure virtual' so it has to be defined in the derived classes else the compiler will complain about the class being abstract. Note that even if a base class has a single pure virtual function, it would become as an Abstract Base class.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This shows an example of C++ virtual function/methods
//This example also covers a pure virtual method
//This also shows an example of Inheritance
#include<iostream>

using namespace
std;

//Base Class
class Shape {
public
:
virtual
void Area(int length, int breadth)
{

cout<<"Shape: Area = "<<length * breadth<<endl;
}

virtual
void Circumference(int length, int breadth) = 0; //pure virtual
};

//Derived class - Inherits Shape as Public
class Rectangle : public Shape {
public
:
void
Circumference(int length, int breadth)
{

cout<<"Rectangle: Circumference = "<<2*(length + breadth)<<endl;
}
};


//Derived class - Inherits Shape as Public
class Square : public Shape {
public
:
//Overloaded Area because for Square length = breadth
void Area(int length)
{

Shape::Area(length, length);
}

//Overloaded Circumference because for Square length = breadth
void Circumference(int length)
{

cout<<"Square: Circumference = "<<(4 * length)<<endl;
}

void
Circumference(int length, int breadth)
{

Circumference(length);
}
};


//Derived class - Inherits Shape as Private as Area and Circumference
//for Square is very different from the Base class
class Circle : private Shape {
public
:
//Overloaded Area
void Area(int radius)
{

cout<<"Circle: Area = "<<(3.14 * radius * radius)<<endl;
}

//Overloaded Circumference
void Circumference(int radius)
{

cout<<"Circle: Circumference = "<<(2 * 3.14 * radius)<<endl;
}

private
:
//Nobody should call these methods
void Area(int length, int breadth) {};
void
Circumference(int length, int breadth) {};
};


int
main()
{

Rectangle r;
cout<<"\n\nRectangle Class - Dimensions 3 x 4"<<endl;
r.Area(3, 4);
r.Circumference(3, 4);

Square s;
cout<<"\n\nSquare Class - Dimensions 3 x 3"<<endl;
s.Area(3);
Shape *s1 = &s; //possible to access derived class through base
s1->Area(3,3);
s.Circumference(3);

Circle c;
cout<<"\n\nCircle Class - Radius is 3"<<endl;
//c.Area(3,3); //- Not Possible as its private in Circle
c.Area(3);
//Shape *c1 = &c; // not possible because conversion from 'Circle *'
// to 'Shape *' exists, but is inaccessible
//c.Circumference(3,3); //- Not Possible as its private in Circle
c.Circumference(3);
return
0;
}




The output of the program is as follows:

1 comment: