I'm starting to learn C++ and coming from a C# background I'm having a lot of problems.
What I want to do is trying to replicate exactly the same thing that I'm doing in the following C# snippet, with C++. This is just a simple implementation of the MVP pattern, which I use quite a lot.
I tried in many different ways to make this work with proper and modern C++ but it's constantly giving me compilation errors which I do not understand properly. Most of them are due to the fact that I'm not able to find a proper way to pass an Interface as a constructor parameter and also to store an Interface as a field of a class. Could someone translate this C# code into a proper C++ code, or at least give me some advice please? Thanks in advance.
NOTE: I'm trying to make headers files with only classes declaration and cpp files with actual implementation.
// This is my C# implementation that I want to convert in C++
public class Program
{
public static void Main()
{
IGameView view = new GameView();
Game game = new Game(view);
view.SetPresenter(game);
}
}
public interface IGameView
{
void SetPresenter(Game game);
}
public class GameView : IGameView
{
public void SetPresenter(Game game)
{
_game = game;
}
Game _game;
}
public class Game
{
public Game(IGameView view)
{
_view = view;
}
IGameView _view;
}
This is the C++ code that I'm trying to make compile. I've put everything here without .h and .cpp for clarity and brevity, but as I said I'm actually separating classes from implementation.
class Game
{
public:
(IGameView& view) : _view(view)
{ }
Game operator=(const Game &);
private:
IGameView& _view;
};
class IGameView
{
public:
virtual ~IGameView() {}
virtual void SetPresenter(const Game) = 0;
};
class GameView : public IGameView
{
public:
GameView();
void SetPresenter(const Game game) override
{
_game = game;
}
private:
Game& _game;
};
int main()
{
IGameView view;
Game game(view);
view.SetPresenter(game);
}