Home > database >  C class declaration after using it
C class declaration after using it

Time:06-02

I want to create method with argument, which links to class declared later. Here's 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 answer, but all of found wasn't helpful. Here's error log:

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

CodePudding user response:

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

CodePudding user response:

You can't.

You must declare it earlier. You can, however, define it later, in some circumstances.

To forward declare a class, write this before it is used:

class Entity;

CodePudding user response:

if you want to use a user defined data type in another class you have to declare it before the use class Entity; then use it in function;

void Attack(Entity target);
  • Related