#Operator overload in an inherited class

7 messages · Page 1 of 1 (latest)

grim aurora
#

Let's say I have a base class NArray with the overloaded * operator:

template <typename dtype = double>
class NArray {
protected:
    std::vector<dtype> data;
    Shape shape;

public:
    NArray operator*(const NArray& other) const {
    if(!same_shape(other))
        throw error::ShapeError(this->shape, other.shape, "multiply");
    else
        return elementWiseOp(other, &util::multiply<dtype>);
    }
};

This works perfectly fine.

I now create a class Matrix that inherits from NArray, but has its own different implementation for the * operator overload:

template <typename dtype = double>
class Matrix : public NArray<dtype> {
protected:
    using NArray<dtype>::data;
    using NArray<dtype>::shape;

public:
    Matrix<dtype> operator*(const Matrix<dtype>& other) const {
    if (!this->shape.same_shape(other.shape)) {
        error::ShapeError(this->shape, other.shape, "multiply");
    }
    auto out_data = util::matmul(
        this->data, this->shape,
        other.data, other.shape
    );
    auto out_shape = Shape::get_product_shape(this->shape, other.shape);

    return Matrix(out_data, out_shape);
    }
};

My problem is the following:
When I use the * operator on a Matrix instance, I get the base class's error message followed by the correct output. How do I mute this error message, or even better, how do I remove the base class's instance of the operator* from Matrix?

Code output:

[ShapeError]: Unable to multiply Vectors. Cannot multiply shapes (2,3) and (3,2).
[[22, 28],
 [49, 64]]

If you want to see the full implementation, check these github links:
https://github.com/abdallahsoliman00/NumCpp/blob/main/NumCpp/Core/Matrix.hpp
https://github.com/abdallahsoliman00/NumCpp/blob/main/NumCpp/Core/NArray.hpp

GitHub

My attempt at making my own NumPy for C++. Contribute to abdallahsoliman00/NumCpp development by creating an account on GitHub.

GitHub

My attempt at making my own NumPy for C++. Contribute to abdallahsoliman00/NumCpp development by creating an account on GitHub.

minor barnBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

simple sequoia
#

Hmm maybe make the base overload virtual and override the operator in derived?

#

I dont have a chance to look too hard

grim aurora
#

@simple sequoia Thanks! That worked perfectly.

minor barnBOT
#

@grim aurora Has your question been resolved? If so, type !solved :)

grim aurora
#

!solved