0

I have a few cpp files and headers to them. The problem is when i try do something like this:

character.cpp

#include "item.h"
class Character {
public:
// variables such as health etc //
    void equip(Item *i){
        equipment.push_back(i);
        this->attc += i->attc;
        this->health += i->health;
        this->luck += i->luck;
        this->mana += i->mana;
        i->equipped = true;
    }
};

character.h

class Character;

item.h

class Item;

item.cpp

#include "item.h"
class Item {
public:
    bool equipped;
    string desc;
    int attc;
    int health;
    int mana;
    bool twoHanded;
    int luck;
};

Expected to work, but instead gets:

pointer to incomplete class type is not allowed

… in i->something line.

I don't really know why it's not working :c

Obsidian
  • 3,719
  • 8
  • 17
  • 30
Boyownik
  • 13
  • 1
  • declare your class functions in the header, implement them in the src file. The error says it doesn't know the implementation of Item when you are already trying to use it. – mfnx Jun 14 '19 at 21:03
  • 3
    Which C++ textbook are you using that suggested structuring your files like this? –  Jun 14 '19 at 21:08
  • Possible duplicate of [When can I use a forward declaration?](https://stackoverflow.com/questions/553682/when-can-i-use-a-forward-declaration) – L. F. Jun 15 '19 at 02:22

1 Answers1

2

Move the class definitions into the header where the cpp files can see them. Right now all the cpp files can see is the forward declaration, and that's only enough for them to know that the class exists, not what's in them.

character.cpp

#include "character.h" // changed from item.h
// body of equip function moved here.
void Character::equip(Item *i){
     ^^^^^^^^^^^ note scope resolution
    equipment.push_back(i);
    this->attc += i->attc;
    this->health += i->health;
    this->luck += i->luck;
    this->mana += i->mana;
    i->equipped = true;
}

character.h

#include "item.h" // added. Easiest way to get knowledge of Item into character.h 
                  // and character.cpp

class Character {
public:
// variables such as health etc //
    void equip(Item *i);
};

There is a case to be made for using a forward declaration in character.h and including item.h in full in character.cpp. Potentially slightly faster build times. This is an intermediate-level issue you should explore later when you are more familiar with the C++ language; for now try to keep things simple.

item.h

#include "item.h"
class Item {
public:
    bool equipped;
    string desc;
    int attc;
    int health;
    int mana;
    bool twoHanded;
    int luck;
};

Moved everything from Item.cpp to Item.h. There is currently no need for an Item.cpp.

user4581301
  • 33,082
  • 7
  • 33
  • 54