Class structure advice

Jan 10, 2016 at 5:24am
I'm making a simple RPG which I'm currently working on a class structure for items.

I'm not sure if this is the best way of doing it and I would appreciate if anyone has any suggestions for improving it. Each of the classes will certainly have more members/functions in the future, but as of right now they are pretty empty. Right now I have the code split up into multiple files as show below.

1
2
3
4
5
6
7
8
9
10
// main.cc
#include <memory>
#include "weapon.hh"
#include "armor.hh"

int main() {
	// Examples of item creation
	auto sword = std::make_unique<Weapon>("Iron Sword");
	auto chestplate = std::make_unique<Armor>("Iron Chestplate");
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// item.cc
#include <iostream>
#include "item.hh"

Item::Item(std::string name) : name(name) {
	std::clog << "Created item with name " << this->Name() << '\n';
}

Item::~Item() {
	std::clog << "Deleted item with name " << this->Name() << '\n';
}

std::string Item::Name() const {
	return name;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// item.hh
#pragma once

#include <cstdint>
#include <string>

class Item {
public:
	Item(std::string);
	~Item();
	std::string Name() const;
protected:
	std::string name;
};

1
2
3
4
5
// equipment.cc
#include <iostream>
#include "equipment.hh"

Equipment::Equipment(std::string name) : Item(name) {}

1
2
3
4
5
6
7
8
9
// equipment.hh
#pragma once

#include "item.hh"

class Equipment : public Item {
public:
	Equipment(std::string);
};

1
2
3
4
5
// weapon.cc
#include <iostream>
#include "weapon.hh"

Weapon::Weapon(std::string name) : Equipment(name) {}

1
2
3
4
5
6
7
8
9
10
11
// weapon.hh
#pragma once

#include "equipment.hh"

class Weapon : public Equipment {
public:
	Weapon(std::string);
private:
	uint32_t damage;
};

1
2
3
4
5
// armor.cc
#include <iostream>
#include "armor.hh"

Armor::Armor(std::string name) : Equipment(name) {}

1
2
3
4
5
6
7
8
9
10
11
// armor.hh
#pragma once

#include "equipment.hh"

class Armor : public Equipment {
public:
	Armor(std::string);
private:
	uint32_t protection;
};
Jan 10, 2016 at 7:12am
Using templates are great for this sort of thing- it allows you to focus more on the result. What kind of game are you thinking of making? Don't forget to actually make the game- it's easy to get caught up in making an engine! (I spent years of my life making engines instead of games)
Jan 12, 2016 at 7:44pm
What sort of template? It's an open world RPG; I wanted to make my own engine from scratch since I'm just doing this for fun. I plan on waiting for the Vulkan API to come out before I do any graphics.
Jan 12, 2016 at 9:26pm
So far so good, but be sure to initialize damage and protection in the constructors for Weapon and Armor respectively.
Jan 12, 2016 at 9:54pm
Yep those need initial values still.
Topic archived. No new replies allowed.