I have to class that use each other but whatever I tried I couldn't achieve to make them work. I just want them to access each other and after days of struggle, I decided to ask here. If someone can point out what I am doing wrong and what I should do instead it would be great.
Edit: I decided to implement one of the solutions which are already on stack overflow and changed my code according to that: I will also share errors this time so maybe we can figure out what's wrong.
I tried to copy this: Resolve build errors due to circular dependency amongst classes
I used class name "Unit" instead of "A" and "Skill" instead of "B"
Skill.h
#pragma once
#include <iostream>
#include <vector>
#include "Unit.h"
using namespace std;
class Skill :
public Unit
{
double _val;
Unit* unitPtr;
public:
Skill(double val):_val(val)
{
}
void SetSkill(Unit* unit)
{
unitPtr = unit;
unitPtr->Print();
}
void Print()
{
cout << "Type:B val=" << _val << endl;
}
// Unit* unitPtr;
vector <Skill *> attacks;
vector <Skill *> utilities;
vector <Skill *> movement;
};
Unit.h
#pragma once
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Skill;
class Unit
{
int _val;
Skill* skillPtr;
public:
Unit(int val) :_val(val)
{
stunned = false;
curSpeed = speed + rand() % 8 + 1;
}
void SetSkill(Skill* skill)
{
skillPtr = skill;
skillPtr->Print(); // COMPILER ERROR: C2027: use of undefined type 'B'
}
void Print()
{
cout << "Type:A val=" << _val << endl;
}
int GetDodge()
{
return dodge;
}
void Setup();
string name;
int maxHP;
//... and other variables
};
Unit.cmp
#include "Skill.h"
#include "Unit.h"
void Unit::Setup()
{
heroes.push_back(new Vestal);
heroes.push_back(new Vestal);
heroes.push_back(new Crusader);
heroes.push_back(new Crusader);
monsters.push_back(new BoneSoldier);
monsters.push_back(new BoneDefender);
monsters.push_back(new BoneSoldier);
monsters.push_back(new BoneDefender);
}
Later on the code, I add some stuff to attacks, utilities, and moment and I want to access them from the Unit object, like below:
heroes[0]->skillPtr->attacks[0]
And I want to be able to access the variables in the Unit.h (like maxHP) from Skill.h
Errors:
Error C2512 'Skill': no appropriate default constructor available
Error C2512 'Unit': no appropriate default constructor available