codescracker


c++

C++ Interfaces



« Previous Tutorial Next Tutorial »


Basically Interface in C++, is used to describe the behaviour of C++ class without talking about a particular implementation of the same class. Here is an example:

class JAVAINTERFACEEXAMPLE
{
   public:
      virtual double get_vol() = 0;
   private:
      double len;
      double bre;
      double hei;
};

C++ Interface Example

Here is an example program illustrating the concept of interface or abstract class in C++ practically

/* C++ Interfaces - Example Program */

#include<iostream.h>
#include<conio.h>
class JAVAINTERFACEEXAMPLE
{
	public:
		// here is a pure virtual function, providing the interface framework
		virtual int get_area()=0;
		void setwidth(int wi)
		{
			wid=wi;
		}
		void setheight(int he)
		{
			hei = he;
		}
	protected:
		int wid;
		int hei;
};
class RECTANGLE:public JAVAINTERFACEEXAMPLE
{
	public:
		int get_area()
		{
			return (wid*hei);
		}
};
class TRIANGLE:public JAVAINTERFACEEXAMPLE
{
	public:
		int get_area()
		{
			return (wid*hei)/2;
		}
};
void main()
{
	clrscr();
	RECTANGLE rob;
	TRIANGLE tob;
	int a, b;
	cout<<"Enter width and height: ";
	cin>>a>>b;
	rob.setwidth(a);
	rob.setheight(b);
	cout<<"Rectangle Area = "<<rob.get_area()<<"\n";
	tob.setwidth(a);
	tob.setheight(b);
	cout<<"Triangle Area = "<<tob.get_area();
	getch();
}

Here are the two sample runs of the above C++ program:

c++ interface

c++ interface example program

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test