0

I'm currently testing some simple AngelScript stuff, and noticed something I find a bit strange when it comes to how objects are initialized from classes.

Let's say I define a class like this:

class MyClass {
    int i;

    MyClass(int i) {
        this.i = i;
    }
}

I can create an object of this class by doing this:

MyClass obj = MyClass(5);

However it seems I can also create an object by doing this:

MyClass obj;

The problem here is that obj.i becomes a default value as it is undefined. Additionally, adding a default constructor to my class and a print function call in each one reveals that when I do MyClass obj = MyClass(5); BOTH constructors are called, not just the one with the matching parameter. This seems risky to me, as it could initialize a lot of properties unnecessarily for this "ghost" instance.

I can avoid this double-initialization by using a handle, but this seems more like a work-around rather than a solution:

MyClass@ obj = MyClass(5);

So my question sums up to:

  1. Can I require a specific constructor to be called?
  2. Can I prevent a default constructor from running?
  3. What's the proper way to deal with required parameters when creating objects?

Mind that this is purely in the AngelScript script language, completely separate from the C++ code of the host application. The host is from 2010 and is not open-source, and my knowledge of their implementation is very limited, so if the issue lies there, I can't change it.

Magnus Bull
  • 1,027
  • 1
  • 10
  • 21

1 Answers1

1
  1. In order to declare class and send the value you choose to constructor try: MyClass obj(5);

  2. To prevent using default constructor create it and use:

.

MyClass()
{
  abort("Trying to create uninitialized object of type that require init parameters");
}

or

{
  exit(1);
}

or

{
  assert(1>2,"Trying to create uninitialized object of type that require init parameters");
}

or

{
  engine.Exit();
}

in case that any of those is working in you environment.

declaring the constructor as private seems not to work in AS, unlike other languages.

arie
  • 36
  • 7
  • I suppose the handle method is the way to go then. As for #2, perhaps the version of AngelScript being used here is too old, because I get an "Expected identifier" syntax error from setting a constructor as `private`. Thank you nonetheless; the handle _does_ work. – Magnus Bull Dec 01 '18 at 10:34
  • I fixed my answer. MyClass @ obj(5); didn't compile (I checked). – arie Dec 11 '18 at 15:35
  • I fixed again my answer, after I checked that declaring of constructor as private realy don't work, as you said. – arie Dec 11 '18 at 16:28
  • 1
    I tried the 4 solutions you added and none seemed to be recognized. They all gave syntax errors as if they were regular functions not matching a signature or `engine` not being declared. If that's supposed to work, it probably relies on something not implemented in my host application. – Magnus Bull Dec 12 '18 at 18:58