Interface Class

If I understood correctly an interface class is an abstract class that does not contain any private functions.

And an abstract class is a class that contains at least on pure virtual method.
For example
Class Creature with function void greet(), will be an abstract class.
The abstract class would be useful for the derived classes. Let's consider the following derived classes:
class Dragon, will greet by spiting fire,
class Mermaid, by singing and so on.

Could someone give me some examples in which an interface class would be useful?

If I understood correctly an interface class is an abstract class that does not contain any private functions.
No, an interface is a class with only pure virtual functions. It doesn't have any code or data. It's usually called an abstract base class.


Could someone give me some examples in which an interface class would be useful?
The usefulness isn't in the class, but in how you can use it.

Consider a function that draws a shape on a canvas.
 
void draw(ICanvase* canvas, IShape* shape);

What if your shape could be loaded at runtime from a shared library (or DLL)? The library only needs to export a factory:
 
IShape* create(const std::string& name);

So the user of the library can load the library and do:
1
2
3
4
5
if (IShape* shape = create("silly_irregular_polygon"))
{
    draw(canvas, shape);
    shape->destroy();
}

Note that in all these examples, we don't know or need to know the actual concrete classes involved. That's kind of the point of using interfaces--it's object oriented programming.
Last edited on
Topic archived. No new replies allowed.