currently I'm trying to write a vector class with two child classes, which are designed to fit 3D for example. Some source here:
1 2 3 4 5 6 7 8 9 10 11 12
template<typename TYPE>
class vec{
public:
TYPE val*;
int dimension;
public:
vec();
vec( TYPE val, int dimension );
vec( vec<TYPE> toCopyFrom );
[etc...]
virtual vec<TYPE>& operator+=( vec<TYPE );
};
and
1 2 3 4 5 6 7 8 9 10 11 12 13
template<typename TYPE>
class vec3D : public vec{
public:
TYPE X;
TYPE Y;
TYPE Z;
public:
vec3D();
vec3D( TYPE val, int dimension );
vec3D( vec3D<TYPE> toCopyFrom );
[etc...]
virtual vec3D<TYPE>& operator+=( vec3D<TYPE );
};
Therefore I've got two questions: is it possible to use val* in the second class as well if I let it point to X. For my understanding a class should have a continuous area in memory, right? So if val = &X, then val[1] == Y ??? Or would this be prone to end up in the middle of invalid memory?
And: Is it possible to kind of re-use the operator overloads and just to update the return value from vec to vec3D ?? Or do I have to rewrite them all?
So I got thisone so far: it seems to be compiler dependent whether structures (which I clearly not have :( ) are serial in memory or not...therefore I won't do that. Any suggestions how I can access val[ ] of parents class by real name X, Y, Z...I suppose I could just use pointers *X -> val[0] and use *X rather than X...but there must be a smoother way??!
Virtual operators suck, by the way. You're going to run into problems there (you can += two vec3D and two vec, but not one of each, for example). Secondly, your copy constructors are infinite recursion.
Yes I was told this already, thanks! My new attempt will be a common base class and a different child for three and many elements each. Then I can have different contructors some specialized functions for the 3D one and (without having more data to store) I use the operators from the baseclass directly...even better I can use it as array pointer as well giving a specialized implementation for certain TYPES while the base stays templated!
Secondly: you mean this one, correct? vec3D( vec3D<TYPE> toCopyFrom );
Why is it infinite recursion? Wouldn't that be a infinite loop to the object itself? How comes?