Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 799
XBigTK13X Avatar asked Jan 20 '11 05:01

XBigTK13X


2 Answers

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.

like image 127
Oswald Avatar answered Oct 02 '22 15:10

Oswald


sf::Sprite GetGraphic() is not correct, it is declaring a global GetGraphic function . Since GetGraphic is a function of the class WorldObject it should be sf::Sprite WorldObject::GetGraphic().

like image 44
Naveen Avatar answered Oct 02 '22 15:10

Naveen