Inter referencing objects

Hi. I am working on making a game with the SFML library. I was wondering how I could use an instance of a class from a different file. My code looks something like this:
Window.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
namespace
{
       sf::RenderWindow window; //This is the object I want to use
       sf::Event Event;
}

Window::Window(int sizeX, int sizeY)
{
       width = sizeX;
       height = sizeY;
       scaleX = (scaleX * (width / 800));
       scaleY = (scaleY * (height / 600));
}

Input.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "Input.hpp"
#include "Window.hpp"

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>

namespace
{
       const sf::Input &input = window.GetInput(); //This returns "'window' was not declared in this scope"
}

Input::Input()
{
      while (input.IsKeyDown(sf::Key::Left)){
              Input::LeftKeyDown = true;}
      Input::LeftKeyDown = false;
...

Last edited on
You are looking for the keyword 'extern' I believe.

The extern keyword allows you to declare a variable anywhere and make it global across all files that have it included in the header.

My suggest to you is to create a header called GlobalVariables.h and include it inside of every file that needs to use your sf::RenderWindow.

GlobalVariables.h:
1
2
3
4
5
6
#ifndef GLOBALVARIABLES_H_INCLUDED
#define GLOBALVARIABLES_H_INCLUDED

extern sf::RenderWindow window;

#endif 


This section of the code just provides it to the other files. Now you have to actually create the variable. Create the variable normally inside of your Main.cpp, but make sure you create it globally.

Hope this helps.
Cheers
Topic archived. No new replies allowed.