I want to have some nice linear algebra in my code with the help of operator overloading. E.g. a product with a vector and a scalar looks like vec * scalar and returns a vector. The problem is, i have 2D and 3D vectors and at compile time is is not know which one it will be.
My attempt was a empty base class and a derived class for 2D and 3D. However it seems like this is not working as expected because it is not calling the correct methods.
#include <cstdlib>
#include <iostream>
class baseVector {
public:
baseVector() {}
~baseVector() {}
virtual void print() {
std::cout << "This is not the vector you are looking for" << std::endl;
}
virtual baseVector operator*(const double r) const {}
};
class Vector2 : public baseVector {
public:
Vector2() {}
Vector2(double x, double y) {
data_[0] = x;
data_[1] = y;
}
~Vector2() {}
void print() {
std::cout << data_[0] << ", " << data_[1] << std::endl;
}
/** Product: Vector * Scalar */
baseVector operator*(const double r) const {
Vector2 result(data_[0]*r,
data_[1]*r);
return result;
}
private:
double data_[2];
};
int main(int argc, char** argv) {
// Construct vector of derived type which is not known at compile time
baseVector * myVec = new Vector2(1, 2);
const double val = 5;
baseVector & tempVec = *myVec;
tempVec.print();
// Some nice linear algebra here, can't use datatype Vector 2 because it is know known at compile time
baseVector resVec = tempVec * val;
// This should print 5, 10
resVec.print();
return 0;
}
I expect resVec to be a vector of type Vector2 with the values 5, 10. Instead it calls the print function of the base class. I understand somehow why this is happening but how do I achiev what I want?
Anyway, is this even the right way to go? Thanks in advance for every hint.
Edit: Slicing is not the answer but explains why it doesn't work. I've found a possible solution with the auto keyword. Skip the inheritance and use auto in the main instead of a specific type. Thanks everyone to make me thinking.