SFML community forums

Help => General => Topic started by: Hengad on September 02, 2015, 06:45:33 pm

Title: Help with error, working with classes
Post by: Hengad on September 02, 2015, 06:45:33 pm
I am doing something wrong here, don't just know what, when compiling it says drawSnake was not declared in this scope. I have just succeeded making pong game, now I am trying to make snake game.

In Game.cpp I call drawSnake like this:
Quote
drawSnake();

Game.h:

Quote
#include <SFML/Graphics.hpp>

#ifndef GAME_H
#define GAME_H

class Game : public Snake
{
    public:
        Game();
};

#endif // GAME_H


In Snake.cpp I have made the drawSnake() function, it doesn't have errors:

Quote
void Snake::drawSnake()
{
    for(int i = 0; i < snake.size(); i++)
    {
        window.draw(snake);
    }
}

Snake.h:

Quote
#include <SFML/Graphics.hpp>
#include <vector>

#ifndef SNAKE_H
#define SNAKE_H

class Snake : public Game
{
    public:
        Snake();
        void drawSnake();
};

#endif // SNAKE_H


Even they are kind of long I tried to shorten them.
Title: Re: Help with error, working with classes
Post by: Satus on September 02, 2015, 07:19:21 pm
class Game : public Snake
class Snake : public Game

What?
Title: Re: Help with error, working with classes
Post by: Hengad on September 02, 2015, 07:24:03 pm
Yup, I need stuff in Game that is in Snake, and vice versa.
Title: Re: Help with error, working with classes
Post by: Satus on September 02, 2015, 07:30:55 pm
Yup, I need stuff in Game that is in Snake, and vice versa.

That is not quite what inheritance is for. You should read some books about C++ and OOP before you start coding games  :)
Title: Re: Help with error, working with classes
Post by: Hengad on September 02, 2015, 07:48:09 pm
Well yes, I ordered 2 books yesterday, but they haven't arrived yet. I know that is not why inheritance is, but in my snake class I need game class for window to draw the snake, and in game class I need snake to use functions in snake class.. How should I do this?
Title: Re: Help with error, working with classes
Post by: Satus on September 02, 2015, 07:56:29 pm
What you probably need is Composition or Aggregation. (http://stackoverflow.com/questions/1644273/what-is-the-difference-between-aggregation-composition-and-dependency)
Make you Snake a field inside Game, and if you need to access Game from Snake (though you should try to avoid child-to-parent relationships if possible), then pass a pointer to Game to you Snake object.
wikipedia (https://en.wikipedia.org/wiki/Composition_over_inheritance#Composition_and_interfaces)