Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading