Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does it make sense to use an abstract class

I'm transitioning from c to c++ and of course, OOP which is proving more difficult than expected. The difficulty isn't understanding the core mechanics of classes and inheritance, but how to use it. I've read book on design patterns but they only show the techniques and paint a vague picture of why the techniques should be used. I am really struggling to find a use for abstract classes. Take the code below for example.

class baseClass {
public:
    virtual void func1() = 0;
    virtual void func2() = 0;
};
class inhClass1 : baseClass {
public:
    void func1();
    void func2();
};
class inhClass2 : baseClass{
public:
    void func1();
    void func2();
};
int main() {}

I frequently see abstract classes set up like this in design books. I understand that with this configuration the inherited classes have access to the public members of the base class. I understand that virtual functions are placeholders for the inherited classes. The problem is I still don't understand how this is useful. I'm trying to compare it to overloading functions and I'm just not seeing a practical use.

What I would really like is for someone to give the simplest example possible to illustrate why an abstract class is actually useful and the best solution for a situation. Don't get me wrong. I'm not saying there isn't a good answer. I just don't understand how to use them correctly.

like image 442
mreff555 Avatar asked Dec 24 '22 20:12

mreff555


1 Answers

Abstract classes and interfaces both allow you to define a method signature that subclasses are expected to implement: name, parameters, exceptions, and return type.

Abstract classes can provide a default implementation if a sensible one exists. This means that subclasses do not have to implement such a method; they can use the default implementation if they choose to.

Interfaces do not have such an option. Classes that implement an interface are required to implement all its methods.

In Java the distinction is clear because the language includes the keyword interface.

C++ interfaces are classes that have all virtual methods plus a pure virtual destructor.

Abstract classes and interfaces are used when you want to decouple interface from implementation. They're useful when you know you'll have several implementations to choose from or when you're writing a framework that lets clients plug in their own implementation. The interface provides a contract that clients are expected to adhere to.

like image 75
duffymo Avatar answered Jan 04 '23 11:01

duffymo