Simply put, I am trying to have textures and other semi-constant objects be prepared within one .h or .cpp file so that they can be used within other files. I want to be able to do something like this:
class Position
{
private:
int x;
int y;
public:
/* constructor, destructor, and other code */
void setPosition(int x, int y) { this->x = x;
this->y = y; }
};
Then, in another file, have something like this:
//otherfile.extension
// I want to be able to declare these objects here...
Position specialPosition1;
Position specialPosition2;
// ...and then be able to do this somewhere where it will keep
// this information for any other file that includes this.
specialPosition1.setPosition(25, 25);
specialPosition2.setPosition(-10, -10);
I want to be able to call their setPosition()
method and prepare them within the same file to be used within other files if possible. Or at least be able to set it up so that the information will exist before it is used anywhere else.
If I recall, making them static would not solve this issue; plus I still have no (known) place to call the setPosition
to prepare the objects. I have also read up a tad bit on extern, though my knowledge of it is only vague.
How might I be able to prepare these objects before main()
, or, to be a bit more precise, what is the "best" way to prepare these objects before they are used in other files?
I don't think you want to call setPosition
at all. I think it would be better to initialize them in the constructor. I assume these special positions are constant.
I think you want to declare them as extern
in a .h file and then define them in a .cpp:
Position.h:
struct Position {
int x;
int y;
Position(int _x, int _y) : x(_x), y(_y) {}
//...
};
SpecialPositions.h:
#include "Position.h"
extern const Position specialPosition1;
extern const Position specialPosition2;
SpecialPositions.cpp:
#include "SpecialPositions.h"
const Position specialPosition1{25, 25};
const Position specialPosition2{-10, -10};
Main.cpp:
#include "SpecialPositions.h"
#include <iostream>
int main() {
std::cout << specialPosition1.x << "\n";
}
Or you could force compile time constants and use constexpr
. Change the Position
constructor to be constexpr
:
constexpr Position(int _x, int _y) : x(x_), y(_y) {}
And then just define them in the SpecialPositions.h file (no need for SpecialPositions.cpp):
constexpr Position specialPosition1{25, 25};
constexpr Position specialPosition2{-10, -10};