How is this private variable "not declared in this scope"?

XBigTK13X picture XBigTK13X · Jan 20, 2011 · Viewed 14.7k times · Source

I'm currently trying to learn more about object oriented design in C++ (familiar with Java) and am running into some walls. The project I am trying to put together to learn these principles in a game built using SFML for the graphics and audio. I have the following two files.

WorldObject.h

#ifndef WORLDOBJECT_H
#define WORLDOBJECT_H
#include <SFML/Graphics.hpp>
#include <string>
#include "ImageManager.h"

class WorldObject
{
 private:
  sf::Sprite _sprite;
  void SetImagePath(std::string path);
  sf::Sprite GetGraphic();
};
#endif

WorldObject.cpp

#include "WorldObject.h"
void WorldObject::SetImagePath(std::string path)
{
  _sprite.SetImage(*gImageManager.getResource(path));
}

sf::Sprite GetGraphic()
{
  return _sprite;
}

I don't see any problem with either of these, and yet when I attempt to compile them I receive the following error from g++:

WorldObject.cpp: In function ‘sf::Sprite GetGraphic()’:
WorldObject.cpp:9: error: ‘_sprite’ was not declared in this scope
make: *** [WorldObject.o] Error 1

What am I missing in this code? Trying to understand the proper way to setup the inheritance hierarchy has been causing the most problems thus far in the game's development, but I know that that is primarily caused by the fact that I am more conditioned to using Java's inheritance model as opposed to C++'s multiple inheritance model.

Answer

Oswald picture Oswald · Jan 20, 2011

The function GetGraphics that you define in WorldObject.cpp is not a member of class WorldObject. Use

sf::Sprite WorldObject::GetGraphic()
{
  return _sprite;
}

instead of

sf::Sprite GetGraphic()
{
  return _sprite;
}

Note that the C++ compiler only complains about the missing WorldObject::GetGraphic if this function is called from somewhere in your program.