Hope you can help me out with this. Consider the following class hierarchy:
class Collider
{
public:
... //Some functions that aren't worth mentioning. They all are abstract so the class is abstract.
}
class CircleCollider : public Collider
{
private:
vec2 pos_;
float radius_;
public:
... //The definition of the parent functions and constructor / destructor.
}
class RectCollider : public Collider
{
private:
vec2 pos_;
vec2 size_;
public:
... // Again, the definition of the parent functions and constructor / destructor.
}
In another class I've got a pointer to the parent class that creates a new instance of one of the two child classes, depending on an enum value, like so:
void SetCollisionType(ECollisionType Type)
{
switch(Type)
{
case CIRCLE:
{
Collider* collider = new CircleCollider(pos, radius);
break;
}
case RECTANGLE:
{
Collider* collider = new RectCollider(pos, size);
break;
}
}
}
Please note I've simplified the function so you get an idea of how my code works. Now what I want to do is a function that updates the member variables of each Child class, radius for CircleCollider, and size for RectCollider. I thought of adding a function to the Collider class:
virtual void UpdateCollider(float NewRadius, vec2 NewSize) = 0;
And then define it in each child class.
void CircleCollider::UpdateCollider(float NewRadius, vec2 NewSize)
{
radius_ = NewRadius;
}
void RectCollider::UpdateCollider(float NewRadius, vec2 NewSize)
{
size_ = NewSize;
}
The problem I see with this is that the definition used in CircleCollider will not use the NewSize parameter, and the same will happen to NewRadius with the definition in RectCollider. However, I cannot think of another way to do it. Do you know another way to do it making use of the hierarchy and polymorphism present in this code? Thank you very much in advance!
{ Collider* collider = new CircleCollider(pos, radius); }is almost certain to create a memory leak, ascollidergoes out of scope almost instantly. Hopefully this part has been simplified and is not actually in your code.