AngelScript - Avoid implicit default constructor from running

274 views Asked by At

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.

1

There are 1 answers

4
arie On BEST ANSWER
  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.