-1

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 */
}
ridhomblr
  • 47
  • 1
  • 9

3 Answers3

1

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();
}
Max Play
  • 3,717
  • 1
  • 22
  • 39
0

Engine::init does not initialize a global object Engine, it's just a static (meaning non-member) function in the namespace of class Engine. If your intention is to write a singleton, then you have to access members of that singleton through a static function:

// within class Engine
static Engine& instance()
{
    static Engine inst;
    return inst;
}

// within main
Engine::instance().mainPlayer = player;

otherwise write a regular C++ constructor and create a single instance of class Engine like the other comment said: https://stackoverflow.com/a/75683067/16062280

-1

mainPlayer doesn't need to be constexpr. That's a choice you as the programmer makes depending upon your requirements.

BUT a member variable is either an instance member or a class member (i.e. static), you can't have it both ways.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
SmittyBoy
  • 289
  • 3
  • 12
  • 1
    If you don't want your answers edited, terminate your account. Collaborative editing is the SO model, and you agreed to it when you accepted the terms and conditions upon signing up. As far as "experience and expertise", certainly not in this sphere. – StoryTeller - Unslander Monica Mar 11 '23 at 12:09