C++ language

Interface in C++
Previous Home Next

Interfaces procure a suitable means of resolving the fash between what a class is and what it can do. deferment interface and implementation distinct in C++ programs deferment designs fresh and support reuse. The C++ interfaces are execution using abstract classes and these abstract classes would not be flurried with data abstraction which is a notion of deferment execution information detached by a pertinent data. An interface show the behavior or abilities of a C++ class without making to a exclusive implementation of that class. It show a bond between a provider and its users, defining what it's required from each promoter, but only in spell of the services they may give, no datum how they manage to do it.

class MyInterface
{
public:
           // Empty virtual destructor for proper cleanup
virtual ~MyInterface() {}

virtual void Method1() = 0;
virtual void Method2() = 0;
};
class MyAbstractClass
{
public:
virtual ~MyAbstractClass();

virtual void Method1();
virtual void Method2();
void Method3();

virtual void Method4() = 0; 
};

 

Abstract Example:-

Interfaces give a suitable means of resolving the problem that sometimes occurs between what a class is and what it can do. When a provide c++ class "implements" few item of interfaces, the pattern of these class could attend any place that an object implementing 1 of whose interfaces is need. That, the interface keyword may be used as a context to a contra sty steady of objects that implement that interface. This might detonation alot as inheritance-based polymorphism, but there is a key distinction Interfaces permit you to fast condition that apply polymorphism to objects that do not provide a general base class. I suppose that by interface i mean a C++ class with only net virtual rule , instead by abstract class i mean a C++ class by virtual methods it could be overridden, and few code, but less than 1 net virtual technique it makes the class not insatiable.

#include <iostream>
using namespace std;
                                // Base class
class Shape 
{
public:
     // pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
                                       // Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{ 
return (width * height); 
}
};
class Triangle: public Shape
{
public:
int getArea()
{ 
return (width * height)/2; 
}
};
int main(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; 
return 0;
}
Previous Home Next