Can't define class functions OUTSIDE class

472 views Asked by At

I want to separate Game class into header and source. To do that I need to be able to define the functions outside the class, but, strangely, I can't!

main.cpp

#include "app.hpp"
int main ()
{
    Game game(640, 480, "Snake");
    game.run();
    return 0;
}

app.hpp

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class App
{
    friend class Game;
    public:
             App(const int X, const int Y, const char* NAME);
        void run(void);
    private: // Variables
        sf::RenderWindow window;
        sf::Event         event;
        sf::Keyboard     kboard;
};
#include "game.hpp"

And now the question part.

game.hpp.

class Game // this snippet works perfectly
{
    public:
             Game(const int X, const int Y, const char* TITLE) : app(X, Y, TITLE)
             { /* and the initialization of the Game class itself... */}
        void run()
             { app.run(); /* And the running process of Game class itself*/};
    private:
        App app;
};


class Game // this snippet produces compiler errors of multiple definitions...
{
    public:
             Game(const int X, const int Y, const char* TITLE);
        void run();
    private:
        App app;
};
Game::Game(const int X, const int Y, const char* TITLE) : app(X, Y, TITLE) {}
void Game::run() { app.run(); } // <<< Multiple definitions ^^^

Why?

2

There are 2 answers

1
Alok Save On BEST ANSWER

What is the reasoning for the multiple definitions error?

Because you are defining the functions in the header file and when you include the header in translation units a copy of the function is created in each translation unit, thus leading to multiple definitions and violation of one definition rule.

What is the solution?

You can define the functions separately but in a cpp file. You declare functions in header file and define them in source cpp file.

Why first example works?

The only standard compliant way to bypass one definition rule is to use inline functions. When you define the functions inside the class body, they are implicitly inline and the program can successfully bypass one definition rule and the multiple definition linking error.

0
jaredready On

Because you're defining class Game twice. Here's how you lay out the separation:

Class.hpp

class Class
{
    public:
        Class();
        void foo();
};

Class.cpp

Class::Class() { //Do some stuff}
void Class::foo() { //Do other stuff }