Constructor Class - How can it instantiate its object?

I have the following situation
Class1
Class2 (super Class1)

Class1 structure:
Class1
| -…
|-+ theClass2 As Class2
| |- property (of Class2)
| -…

This example works:

Var myClass1 As New Class1
Var myClass2 As New Class2
myClass1.theClass2 = myClass2

myClass1.theClass2.prop= 33
MessageBox (Str (myClass1.theClass2.prop))

I would like to use Class1 constructor and I wished that Class1 constructor would create automatically theClass2 instance.
So I did this, but it didn’t work:

Var myClass1 As New Class1

myClass1.theClass2.Untitled = 33
MessageBox (Str (myClass1.theClass2.prop))

How can I write the costructor ?

Add a new method in Class1 named Constructor then add the code:
theClass2 = New Class2

1 Like

It was what I expected.

So there is something wrong with an XoJo project.
That project tells me: “An exception of class StackOverflowException was not handled. The application mus shut down.”
But if I create a new project it gives me no exception.

In my OneDrive you found two IDENTICAL projects and cleaned up from everything:

  • TESTqua: the project that gives me the exception
  • ClassTest: that works

Now I would like to understand what XoJo wants to me.
And how to solve problems of this type, because if it happens in my real project, I will not to rewrite it from scratch because XoJo has a tantrum.

Thanks,
and looking forward to solving the mystery.

The problem is because you have made Class2 a subclass of Class1.
Since Class2 has no Constructor it calls the super Constructor which is Class1.Constructor. This then creates a new instance of Class2 so it repeats infinitely.

If you clear the Super property for Class2 so that it is no longer a subclass of Class1 it should work.

You are right, I’m so stupid.
It was enough to create the constructor in Class2.

I slipped on a banana peel.

Thanks @keving

Actually, Class2 can be a sub-class of class1. It just needs a constructor method AND the constructor method for Class2 cannot call Super.Constructor which would end up creating an infinite loop.

1 Like

Agreed, although that seems a bit of an iffy design to me.

I would tend to agree.

I also think that creating a second object from the constructor of a first is also iffy unless that new object is a properly of the first object.