How do i reference a nonstatic member of a class in C++

I am writing a header file, i am trying to change a variable in the main class, but an error pops up:

"a nonstatic member must be relative to a specific object"

I am not trying to make an object, and the variable must be nonstatic, The solutions i found involve making an object, or making it a constexpr static, while that works, it would make it unmodifiable

Engine.h:

class Engine {
public:
    playerObject2D mainPlayer;
    /* other definitions */
};

main.cpp:

#include "Engine.h"
playerObject2D player;

int main(int argc, char* argv[]){
    Engine::init(640, 480, "Test", 0, 0, 0, argc, argv);
    player.setPos(320,240); /* set player positon to center of screen */
    player.pspd = 8; /* set player speed */
    
    Engine::mainPlayer = player; /* Error */
}

>Solution :

You have to use one of the ways to create an instance of a class.

class Engine
{
public:
    void DoStuff() {}
};

You can either do it directly on the stack

int main(int argc, char* argv[])
{
    Engine engine;
    engine.DoStuff();
}

Or you can create it on the heap and access it via pointer.

int main(int argc, char* argv[])
{
    Engine* engine = new Engine();
    engine->DoStuff();
}

Leave a Reply