Tuesday, 5 May 2009

An example of Interface class

Sometimes it is simple and helpful to define a class that does nothing but defines a standardised interface that can be used by other classes to make sure the implementation follows a standard set of input and output paramaters. Also this approach results in faster code runs and more maintainable code.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows an example of Interface class

#include<iostream>

using namespace
std;

//Shape is an Interface Class. No data and everything pure virtual
class Shape {
public
:
virtual
void Area(int length, int breadth) = 0;
virtual
void Perimeter(int length, int breadth) = 0;
//Note, no data
};

//Derived class - Inherits Shape as Public
class Rectangle : public Shape {
public
:
void
Area(int length, int breadth);
void
Perimeter(int length, int breadth);
private
:
int
someData;
};


//Derived class - Inherits Shape as Public
class Triangle : public Shape {
public
:
void
Area(int length, int breadth);
void
Perimeter(int length, int breadth);
private
:
int
someData;
};


int
main()
{

Rectangle r;
Triangle t;

cout<<"\n\n";
r.Area(3,4);
r.Perimeter(3,4);

t.Area(3,4);
t.Perimeter(3,4);

cout<<"\n\n";
return
0;
}


void
Rectangle::Area(int length, int breadth)
{

cout<<"\nThe Area of Rectangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)<<endl;
}


void
Rectangle::Perimeter(int length, int breadth)
{

cout<<"\nThe Perimeter of Rectangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<2 * (length + breadth)<<endl;
}


void
Triangle::Area(int length, int breadth)
{

cout<<"\nThe Area of Triangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)/2<<endl;
}


void
Triangle::Perimeter(int length, int breadth)
{

cout<<"\nThe Perimeter of Triangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)/3<<endl;
}


In the above example, Shape class is an 'abstract class'. All the interfaces are 'pure interfaces'. It contains no data. The derived classes now have to define the interace functions.

The output is as follows:

No comments:

Post a Comment