Changine an instance of a class to another class (C++)

Started by
1 comment, last by Ra 15 years, 8 months ago
Ok, I have an object of one class, and I want to pass it to a function which is set to take an object of another class. What would be the best way of going about this? Hopefully an example will make some sense out of my question. Say I'm using two libraries, a physics library and a graphics library. Each of these has their own 3D vector class. I have an object which needs to send data to both these libraries.

//physics library
void Physics::MoveObject( physVector pos )
{};

//graphics library
void Graphics::RenderObject( graphicsVector pos )
{};

//my code
class Entity
{
     MyVector pos;
};

void Update()
{
   Entity ent;

   Physics::MoveObject( ent.pos );
   Graphics::RenderObject( ent.pos );
}
Is there a way to do this? By writing some method in MyVector that will convert itself to either a graphicsVector or a physVector? Or do I end up with,

Physics::MoveObject( ent.pos.ToPhysVector );
Graphics::RenderObject( ent.pos.ToGraphicsVector );
And if that's the case, what's the best way of doing that? Cheers, Zenix.
Advertisement
You can make your class be able to be implicitly converted to another type like this:
class MyVector{public:	float x, y, z;	operator OtherVector() { return OtherVector(x,y,z); }};
You can write conversion operators for your class to allow it to be implicitly converted to either vector type.

class MyVector
{
...

operator physVector() const
{
return physVector(...);
}

operator graphicsVector() const
{
return graphicsVector(...);
}
};

If your class has binary compatibility with either of these vector types you could potentially return by-ref rather than by-value from the conversion operators and reinterpret_cast as necessary, but that's treading into dangerous territory.
Ra

This topic is closed to new replies.

Advertisement