Yea seems like it might be useful when casting during runtime. I have read that dynamic_cast is useful when using polymorphic classes, though I am having trouble using it. I can compile fine but when I try use a function from a derived class that I have dynamic casted, I get a crash (possible that it is returning a nullptr, though I run a condition that if NOT nullptr execute some code - use derived function.
Im trying to use it with physX API and obviously I can change the API to suit my needs as I only want to implement my own makeshift code to use their already made polymorphic classes (I get scared having to use code I know very little about, though after looking at their definition it looks like it should work - I have probably greatly misunderstood how dynamic_cast's are used).
What I want
Store polymorphic shape's into a std::vector<baseClass>
Pass a shape into a function
Then run a derived function on that shape if shape is a correctly derived shape
- some shapes can move and others do not
- therefore only the shapes that move have an applyForce(vec3(x,yz))
Given that I have a container of different shapes:
- i loop through the std::vector<baseClass> and pass each shape to the function that will run
applyForce(vec3(x,yz))
- i can only pass the base shape in and then cast the shape to the appropriate derived class
for the shapes that are able to move
- or just cast the shape to the appropriate derived class when passing it
- therefore I want to use dynamic_cast to run the ritti check during "runtime" and only
the shapes that are from derived class that are moveable with have the function
applyForce(vec3(x,yz)) applied to them given whether they are NOT a nullptr
Brief look at the PhysX classes to be used
Code: Select all
class BaseShape
{
baseShape();
virtual void createShape(parameters....) = 0;
};
class MoveableShape : public baseShape
{
moveableShape();
virtual void createShape(parameters....);
applyForce(vec3 force);
};
class staticeShape : public baseShape
{
staticeShape();
virtual void createShape(parameters....);
//given this shape will never move it doesn't need and applyForce(vec3 force);
};
void applyForceIfCanMove(baseShape* shapeCanMove)
{
if(shapeCanMove != nullptr)
{
if(spaceBarPressed)
{
shapeCanMove->applyForce(vec3(0,100,0));
}
}
}
int main()
{
std::vector<baseShape*> allShapes;
baseShape* newShape;
newShape = new moveableShape;
newShape.createShape(parameters....);
allShapes.push_back(newShape);
newShape = new staticeShape
newShape.createShape(parameters....);
allShapes.push_back(newShape);
for(auto shape : allShapes)
{
applyForceIfCanMove(dynamic_cast<moveableShape*>(shape));
}
return 0;
}
[/size]
But is crashes at runtime when dynamic_cast is used. Though, it works when static_cast is used????
WHY?