-4

I'm trying to make a multiplayer game with Unity3D and a .Net console application as a server.

Now I've made a mainGame class which inherits the ServerTime class which should also be initialised upon the creation of the maingame class (hence it is in the constructor of maingame)

The problem though is, that it throws a Stack overflow on the constructor of ServerTime.

public class Program
{
    public static void Main()
    {
        new mainGame("JustAName");
    }

    public class mainGame
    {
        public ServerTime serverTime = null;
        public mainGame(string a_Roomnme)
        {
            serverTime = new ServerTime(null);
        }
    }

    public class ServerTime : mainGame
    {
        public ServerTime(string roomName): base(roomName)
        {
            //Do something
        }
    }
}

As it is just simply passing the string to ServerTime I don't see where it could lead to such an exception.

Thank you in advance

cc500
  • 13
  • 1
  • 2
    `mainGame` initializes a `ServerTime` object which calls the `mainGame` base class which creates a `ServerTime` object and so on. Should be pretty obvious in the call stack – Ňɏssa Pøngjǣrdenlarp Sep 08 '21 at 21:56
  • 2
    new mainGame -> serverTime -> new mainGame -> serverTime -> new mainGame -> serverTime -> new mainGame -> serverTime -> new mainGame -> serverTime -> new mainGame -> serverTime -> new mainGame -> serverTime `¯\_(ツ)_/¯` – TheGeneral Sep 08 '21 at 21:57
  • 1
    If you asked someone to get you a coffee, and they asked what sort, and you asked them to get you a coffee, what do you expect to happen? You get stuck in an endless loop. now, if you have to write down every time you asked them to get a coffee to keep track of the request, then your are going to run out of paper. Something has to give – TheGeneral Sep 08 '21 at 21:58

1 Answers1

0

The main function initializes a mainGame object. This object has a ServerTime member. The ServerTime member is initialized, but since ServerTime inherits from mainGame, it calls its parent's constructor - meaning it initialized another ServerTime object, and so on, endlessly (or, at least, until a stack overflow exception is thrown).

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • That makes sense but if I remove The serverTime object (and the line : serverTime = new ServerTime(null)) The constructor of ServerTime isn't being called. Shouldn't that happen if it's already being initialized by the mainGame constructor? – cc500 Sep 08 '21 at 22:03
  • @cc500 yup, exactly – Mureinik Sep 08 '21 at 22:05