简体   繁体   中英

Is it an abstract class or a pure virtual (interface)?

It might be a silly question but I never saw a question about it or read about it.

Imagine that we have this:

class Numeric
{
public:
    virtual ~Numeric() {}
    virtual int getNumeric() const = 0;
};

This is considered an interface.

And now I insert an enumerator (It can be something else, like a typedef, etc.)

class Numeric
{
public:
    enum Numbers
    {
        One,
        Two,
    };

    virtual Numbers getNumeric() const = 0;
};

Still being an interface or it is now considered an abstract class?

As I said, it might be silly but I really wonder to know that.

If you are looking for an official answer, then I'm afraid there is none.

The draft of the C++11 standard I am having here merely says [10.4 class.abstract]:

An abstract class can also be used to define an interface for which derived classes provide a variety of implementations.

All other instances of the word "interface" in the entire ~1300 pages PDF only refer to generic programming or other things not related to OOP or abstract classes.

For example this one here [24.2.1 iterator.requirements.general]:

Most of the library's algorithmic templates that operate on data structures have interfaces that use ranges.

This obviously has nothing to do with abstract classes.

Bjarne Stroustrup himself, if you accept his words as "half-official", doesn't really help you in this regard, either. Quoting from the glossary on his homepage :

abstract class - a class defining an interface only; used as a base class.

You will have to live with the fact that the C++ language itself as well as C++ developers and experts use the word "interface" as a superset for "abstract class" . Unlike eg in Java, where interfaces are an actual language element with its own interface keyword, there is no such thing in C++.

Everything else is opinion-based.

Your second class Numeric is an interface.

If a class has one or more pure virtual functions, then this class is called an "abstract class".

Generally, if all of a classes' functions are pure virtual functions, then this class is called an "interface".

C++ does not have an explicit interface concept, so the above two classes are called the interface or abstract class, somewhat interchangably.

In my opinion, your second class can be considered an interface. I don't think there is a standard which defines interfaces in C++. However in languages which have interfaces, for example, Java, you can usually have enums defined inside an interface.

I would consider a class with no implementation to be an interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM