calling up a class that is nested in another class

umm, how do you call a class that you have made if it is nested in another one? would it be
 
weapon.longsword


to call up what has been put in to this class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class weapon
{
class longsword
{
public:
int cost,range;
string dmg, dmgtype, size;
cost = 20;
dmg = (rand()%7) +1;
range = 5;
dmgtype = "slashing";
size = "one handed";
};
};
You can't access it via "weapon.longsword", unfortunately. If there is no access specifier, it is automatically private, which means that you can't use that notation. You need to use "public:" before you declare class longsword:
1
2
public:
  class longsword


Secondly, you would use the :: operator (the scope resolution operator), not the . operator (member access operator when using objects):
weapon::longsword

Lastly, my compiler has issues with you assigning values to variables outside of a function. You might use a constructor for the longsword class.


I would rewrite your code, but I don't think a nested class is the way to go.

After all, a longsword is of type weapon, not a part of a weapon, right? Wouldn't inheritance be better for this?
Last edited on
Following on from rpgfan3233, it looks like what you might really want is a class weapon of which longsword is an instance (as you are setting the values for the longsword).
You would then have other instances of the class weapon such as mace, spear, club, etc. all of which would have different values for the data members of the class.
A more generic way to handle this would be to have the weapon name as part of the class, and then you could have an array of weapon to hold all the details for you.

Topic archived. No new replies allowed.