Search code examples
c++inheritanceinterfaceoperator-overloadingabstract-class

C++ Abstract Base Class with pure virtual operator+ function


Let's say I am creating an Abstract Base Class for the purpose of defining a public interface. I want operator+ to be a part of this public interface. It would seem that this is not possible in C++ or that I am missing something.

For example, suppose the code below is a .h file declaring the public interface for an abstract base class named IAbstract. This code does not compile because I cannot declare a function that returns an instance of an abstract base class. This compile error makes sense, but what I don't understand is this: Is there any way to guarantee operator+ will exist in the public interface of IAbstract?

#include <iostream>

// An abstract base class
class IAbstract
{
public:
    IAbstract(int value);
    virtual ~IAbstract() {}
    virtual int SomeOtherFunction() =0;

    //This is ok
    virtual IAbstract& operator++() =0;

    //This will not compile
    virtual const IAbstract operator+(const IAbstract& rhs) =0;
    //Xcode5 says "Semantic Issue: Return type 'IAbstract' is an abstract class"
};

Solution

  • No, it is not possible guarantee operator+ will exist in the public interface of IAbstract-derived classes because you cannot properly declare operator+ as a pure virtual function.