-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

3
  • 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 Commented Sep 8, 2021 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 ¯\_(ツ)_/¯ Commented Sep 8, 2021 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 Commented Sep 8, 2021 at 21:58

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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 yup, exactly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.