I am writing an enemy class for a 2D tile-based game and it seems necessary to instantiate all private members of the class. This leads to some design difficulties, as I need to pass in 10+ arguments into the constructor. How should I go about cleaning this up, as it is necessary to initialize these values when the object is created?
Here is the code:
class Enemy {
private:
SDL_Rect pos;
int health;
int type;
int id;
SDL_Texture* default_texture;
Animation walking_animation;
Animation attack_animation;
std::vector<Item> drop_when_killed;
double velocity_x;
double velocity_y;
double attack_range; // in terms of pixels
int walking_speed;
int jump_height;
public:
explicit Enemy(SDL_Rect pos_, int health_, int type_, int id_,
SDL_Texture* default_texture_, Animation walking_animation_,
Animation attack_animation_, std::vector<Item> drop_when_killed_, double attack_range_,
int walking_speed_, int jump_height_);
: pos(pos_), health(health_), type(type_), id(id_), default_texture(default_texture_),
walking_animation(walking_animation_), attack_animation(attack_animation_),
drop_when_killed(drop_when_killed_), attack_range(attack_range_),
walking_speed(walking_speed_), jump_height(jump_height_) {};
void WalkToPlayer(SDL_Rect player_pos);
void AttackPlayer(Character& ch);
void TakeDamage(int damage_num);
void Die();
void Update(Character& ch);
SDL_Rect GetPos() const;
~Enemy();
};
Velocity
instead of your 2 double for example. - Jarod42struct
that is then passed to the ctor instead of individual arguments.. sometimes that's nicer. - Jesper Juhlstd::move
d at the callsite (because the programmer decided they could be). Though there should be astd::move
in the member-initialiser (drop_when_killed(std::move(drop_when_killed_))
). Your solution of aconst
reference prevents the move case, with no gain for the copy case. - Asteroids With Wings