Search code examples
c++classheader-filesdeclaration

C++ class declaration after using it


I want to create method with an argument which links to Enemy which is declared later. Here is my code:

#include <iostream>
#include <vector>
using namespace std;
class Weapon{
    public:
        int atk_points;
        string name;
        string description;
        void Attack(Entity target){
            
        };
};
class Armor{
    public:
        int hp_points;
        string name;
        string description;
        int block_chance;
};
class Entity{
    public:
        int hp;
        int atk;
        string name;
        vector<Weapon> weapons;
        vector<Armor> armors;
};

I tried to search for answers, but nothing I found was helpful. Here's error log:

prog.cpp:9:15: error: ‘Entity’ has not been declared
   void Attack(Entity target){

Solution

  • The problem is that the compiler doesn't know what Entity is at the point where you have used as a parameter type. So you need to tell the compiler that Entity is a class type.

    There are 2 ways to solve this both of which are given below:

    Method 1

    To solve this you need to do 2 things given below:

    1. Provide a forward declaration for the class Entity.
    2. Make the parameter of Attack to be a reference type so that we can avoid unnecessary copying the argument and also since we're providing a member function's definition instead of just declaration.
    class Entity; //this is the forward declaration
    class Weapon{
        public:
            int atk_points;
            string name;
            string description;
    //------------------------------v------------>target is now an lvalue reference
            void Attack(const Entity& target){
                
            };
    };
    

    Working demo

    Method 2

    Another way to solve this is that you can provide just the declaration for the member function Attack' inside the class and then provide the definition after the class Entity's definition as shown below:

    class Entity;   //forward declaration
    class Weapon{
        public:
            int atk_points;
            string name;
            string description;
    //------------------------------v----------->this time using  reference is optional
            void Attack(const Entity& target);  //this is a declaration
    };
    //other code here as before
    
    
    class Entity{
        public:
            int hp;
            int atk;
            string name;
            vector<Weapon> weapons;
            vector<Armor> armors;
    };
    
    //implementation after Entity's definition
    void Weapon::Attack(const Entity& target)
    {
        
    }
    

    Working demo