Search code examples
c++interfaceabstract

Writing interface for Matrix


I am writing an Interface for Matrix class in C++
So all functions need to be virtual
Now in the below code I have defined a virtual function virtual Matrix add(Matrix A, Matrix B) const = 0;
The problem I see is the class Matrix is not defined. So I am confused should I define the
class Matrix in the interface ? Or is there a better way to implement the interface

class MatrixInterface
    {
    public:
       
        virtual Matrix add(Matrix A, Matrix B) const = 0;
    };

The updated code that's giving compilation error :
In Matrix.cpp add method : member function declared with 'override' does not override a base class memberC/C++(1455)

#include <iostream>
#include "MatrixInterface.h"
class Matrix : public MatrixInterface
{
public:
    Matrix *add(MatrixInterface *A, MatrixInterface *B) override{
        // implementation
    };
};


class MatrixInterface
{
public:
    virtual MatrixInterface *add(MatrixInterface *A, MatrixInterface *B) const = 0;

};

Solution

  • Return the interface type from the add method in your interface class, then in the subclass, you can override the virtual method and change the return type to Matrix (or any narrower type).

    class MatrixInterface
    {
    public:
        virtual MatrixInterface* add(MatrixInterface* A, MatrixInterface* B) const = 0;
    };
    

    Derived class:

    class Matrix : public MatrixInterface
    {
    public:
        Matrix* add(MatrixInterface* A, MatrixInterface* B) override 
        { 
            // implementation
        };
    };
    

    You will need to use pointers to take advantage of covariant return types.