Operator ancestors

Sep 1, 2011 at 1:09pm
Hi guys,

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?

Best, ZED

Sep 1, 2011 at 4:29pm
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??!
Sep 2, 2011 at 3:14am
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.
Sep 2, 2011 at 5:03am
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?

Thanks!
Sep 2, 2011 at 5:15am
For the 2nd one, it is because your toCopyFrom argument is passed by copy, which requires the copy constructor to be called...repeated forever.
Sep 2, 2011 at 5:16am
Oh I see, thanks...!
Topic archived. No new replies allowed.