C++ friend a function in a separate namespace

969 views Asked by At

I'm having issues with my code.

I have a class called Engine:

// Engine.h
#include "SaveLoad.h"

class Engine {
    friend void SaveLoad::save(Engine& engine);
    friend void SaveLoad::load(Engine& engine);
public:
...

The concern here is I want the functions save() and load() to be able to access and manipulate Engine's private data members freely, which is why I friended them. SaveLoad is actually a namespace in another header file, as shown below:

// SaveLoad.h
#include "Engine.h"

namespace SaveLoad {
    void save(Engine& engine);
    void load(Engine& engine);
}

All seems fine so far. Next I call the load() function from Engine's constructor to load the application's saved data:

// Engine.cpp
Engine::Engine(...) {
    ...
    SaveLoad::load(*this);
}

I've passed the Engine to the load() function so load() can update Engine's data members when the application is launched.

After compiling, I get literally 22 error messages, some seemingly absurd and others just down right confusing. Some of these errors are:

  • 'Engine' undeclared identifier -- saveload.h
  • 'save' illegal use of type 'void' -- saveload.h
  • 'load' illegal use of type 'void' -- saveload.h
  • 'SaveLoad::save' not a function -- engine.h
  • 'SaveLoad::load' not a function -- engine.h
  • 'SaveLoad' is not a class or a namespace -- engine.h

And directed at the SaveLoad::load(*this) line:

  • term does not evaluate to a function taking 1 argument -- engine.cpp

I'm guessing this has something to do with the fact that I'm trying to friend functions that are part of a namespace instead of a class or it has something to do with the #includes, but I'm really out of ideas when it comes to playing with the code.

0

There are 0 answers