An
interface describes the behavior or capabilities of a C++ class without
committing to a particularimplementation of that class.
The C++
interfaces are implemented using abstract
classes and these abstract classes should not beconfused with data
abstraction which is a concept of keeping implementation details separate from
associateddata.
A class
is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual
functionis specified by placing "= 0" in its declaration as follows:
classBox
{
public:
// pure virtaul function
virtual double getVolume() = 0;
private:
doublelength; // Length of a box
doublebreadth; // Breadth of a box
doubleheight; // Height of a box
};
The
purpose of an abstrac t c lass(often
referred to as an ABC) is to provide an appropriate base class fromwhich other
classes can inherit. Abstract classes cannot be used to instantiate objects and
serves only as aninterface.
Attempting to instantiate an object of an abstract class causes a compilation
error.
Thus, if
a subclass of an ABC needs to be instantiated, it has to implement each of the
virtual functions, whichmeans that it supports the interface declared by the
ABC. Failure to override a pure virtual function in a derivedclass, then
attempting to instantiate objects of that class, is a compilation error.
Classes
that can be used to instantiate objects are called concrete c lasses.
Abstract Class Example:
Consider
the following example where parent class provides an interface to the base
class to implement a function called g etArea():
#include <iostream>
using namespace std;
//Base class
classShape {
public:
// pure virtual function providing interface framework.
virtualintgetArea() = 0;
voidsetWidth(intw)
{
width= w;
}
voidsetHeight(inth)
{
height= h;
}
protected: intwidth; intheight; };
// Derived classes
classRectangle: public Shape
{
public: intgetArea()
{
return(width * height);
}
};
classTriangle: public Shape { public:
intgetArea()
{
return(width * height)/2;
}
}; intmain(void)
{
Rectangle Rect;
Triangle Tri; Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout<<"Total
Rectangle area: " <<Rect.getArea() <<endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout<<"Total
Triangle area: " <<Tri.getArea() <<endl;
return0;
}
When the
above code is compiled and executed, it produces the following result:
Total Rectangle area: 35
Total Triangle area: 17
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.