Home > front end >  Call a function that takes in a pointer to the current class from inside the class
Call a function that takes in a pointer to the current class from inside the class

Time:01-10

I am trying to call a method outside of the Entity class that takes in an entity pointer as a parameter, and I am getting this compiler error:

C3861: 'PrintEntity': Identifier not found

My code looks like this:

#include <iostream>

class Entity {
public:
    int x, y;

    Entity() {
        this->x = 0;
        this->y = 0;
    }

    Entity(int x, int y) {
        this->x = x;
        this->y = y;

        PrintEntity(this);
    }

    int GetX() const {
        const Entity* e = this;
    }
}; 

void PrintEntity(Entity* e) {
    std::cout << e->x << ", " << e->y << std::endl;
}

int main() {
    Entity e(5, 5);
}

(This isn't practical code, but more of a proof-of-concept exercise)

I understand that this error is occurring because I have not defined a prototype for PrintEntity, and so the Entity class does not recognize the PrintEntity() function when it is called in the Entity constructor, but when I define a prototype just before the Entity class declaration like this:

void PrintEntity(Entity* e);

class Entity {
    ...
}

I get these 5 errors:

C2182: 'PrintEntity': illegal use of type 'void'
C2065: 'Entity': undeclared identifier
C2065: 'e': undeclared identifier
C2064: term does not evaluate to a function taking 1 arguments
C2365: 'PrintEntity': redefinition; previous definition was 'data variable'

My understanding of why these errors are occurring is that the PrintEntity() prototype does not recognize the Entity class, as it has not been defined yet.

So if I cannot write the prototype before the class definition because Entity has not been defined, and I cannot call the PrintEntity() method without prototyping it, how can I make this code work while still being able to call PrintEntity() inside of the Entity class?

CodePudding user response:

One solution is to forward declare Entity and PrintEntity before the class definition and implement PrintEntity after the class definition:

class Entity;

void PrintEntity(Entity*);

class Entity {
    // ...
};

void PrintEntity(Entity* e) {
    std::cout << e->x << ", " << e->y << std::endl;
}

Demo
(Note that GetX doesn't return an int as it promised to do. That must be fixed)

It does look like you would be better off creating a header file with a class definition without member function implementations though. You should move those to a .cpp file instead.

  •  Tags:  
  • Related