How do I instantiate an object within an object?

Heyy what im trying to do in this program is create a new instance of another class within a class. Im having trouble doing so, iv already tried defining the 'Weapon' class within the 'Enemy' class through its constructor, didnt quite work though... I could play around with it for hours on end until i figure it out, i'd rather not though. Iv provided my code below. Can anyone help? would be appreciated, thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//Programmed by: Ricky Wild
//Description:        A short text based console game using classes and pointers.

#include<iostream>
#include<string>
#include<stdlib.h>

using namespace std;

class Weapon
{
public:
	string m_Name;
	string m_Material;
	int m_Condition;
	int m_Damage;
	int m_Price;
	Weapon(string name, string material, int condition, int damage, int price); //constructor prototype..
};

Weapon::Weapon(string name, string material, int condition, int damage, int price) //Weapon class constructor..
{
	m_Name = name;
	m_Material = material;
	m_Condition = condition;
	m_Damage = damage;
	m_Price = price;
}

class Armor
{
public:
	string m_Name;
	string m_Material;
	int m_Condition;
	int m_Defence;
	int m_Price;
	Armor(string name, string material, int condition, int defence, int price); //constructor prototype..
};

Armor::Armor(string name, string material, int condition, int defence, int price) //Armor class constructor..
{
	m_Name = name;
	m_Material = material;
	m_Condition = condition;
	m_Defence = defence;
	m_Price = price;
}

class Enemy
{
public:
	int m_Health;
	int m_Attack;
	int m_Defence;
	int m_Strength;
	int m_Reflex;
	int m_Speed;
	Weapon m_EnemyWeapon = new Weapon("Longsword", "Iron", 2, 5, 50);
	Enemy(int health = 0, int attack = 0, int defence = 0, int strength = 0, int reflex = 0, int speed = 0); //constructor prototype.. 
};

Enemy::Enemy(int health, int attack, int defence, int strength, int reflex, int speed) //Enemy class constructor prototype.. 
{
	m_Health = health;				
	m_Defence = defence;		
	m_Strength = strength;		
	m_Reflex = reflex;
	m_Speed = speed;
}

void main()
{

	system("pause");
}
Just put the object in your class like you do with any other member var, and put its ctor arguments in the initializer list of your constructor.

1
2
3
4
5
6
7
8
9
10
11
12
class Enemy
{
 // ...
  Weapon m_EnemyWeapon;
};

// -- the ctor
Enemy::Enemy(int health,int attack /*...*/)
  : m_EnemyWeapon("Longsword", "Iron", 2, 5, 50)   // initializer list
{
  // ctor body
}
Haha is that it? ah thanks alot :]
Topic archived. No new replies allowed.