Jeffrey Chen
Jeffrey Chen

Reputation: 237

virtual Operator overloading

I am making a GVector class that contains will further derive into 3 types i.e
PVector (Pixel Space Vector)
MVector (Meter Space Vector)
RVector (Rendering Space Vector)

class GVector {
  public : 
    eVectorSpace eVS; // Defines which space the vector would be
    float x,y; // The x and y values of a 2-Dimensional vector
    ...
    GVector operator+ (const GVector& v) const { return GVector(x+v.x, y+v.y, v.eVS); }
    ...
};

class MVector {
  public :
    PVector toPVector() {...}
    //Will contain functions to convert the same vector into a different space
};

I want to make it possible to add 2 vectors lying in the same space

MVector operator+ (const MVector& v) const { return MVector(x+v.x, y+v.y); }  

Do I need to make the base class function like this ?

virtual GVector* operator+ (const GVector* v) const () = 0;  

But I would like to return a vector in the same space as the two adding vectors.

The function of adding the values of the x,y are same for each type of vector. Is there a way to minimize this into the base class itself ? Or is there a better approach to adding vectors in the same space and converting them into different spaces ?

Upvotes: 1

Views: 1463

Answers (2)

Nathan
Nathan

Reputation: 4937

Some code somewhere needs to know how to add two of the vector objects together, but it doesn't actually need to be the vector types themselves. You can define a set of addition operators outside the classes.

MVector operator+(const MVector &left, const MVector &right) {
    return MVector(left.x + right.x, left.y + right.y);
}

You can define as many different operator adds like this as you want, so long as the compiler can figure out what the types are without ambiguity. You can even provide implementations that accept a MVector and a GVector.

MVector operator+(const MVector &left, const RVector &right) {
    MVector tmp = right.toMVector();
    return MVector(left.x + tmp.x, left.y + tmp.y);
}

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798784

If it makes no sense to perform operations on two different children then the operator should not be defined on the parent. Instead a protected helper function can be defined, and then the children should implement the operator separately, delegating to the helper function.

Upvotes: 2

Related Questions