| AngelScript |

Loading...
Searching...
No Matches
Class constructors

Class constructors are specific methods that will be used to create new instances of the class. It is not required for a class to declare constructors, but doing so may make it easier to use the class as it will not be necessary to first instantiate the class and then manually set the properties.

The constructors are declared without a return type, and must have the same name as the class itself. Multiple constructors with different parameter lists can be implemented for different forms of initializations.

      class MyClass
      {
        // Implement a default constructor
        MyClass()
        {
        }

        // Implement the copy constructor
        MyClass(const MyClass &in other)
        {
          // Copy the value of the other instance
        }

        // Implement other constructors with different parameter lists
        MyClass(int a, string b) {}
        MyClass(float x, float y, float z) {}

        // Implement conversion constructors
        // The second can only be used explicitly
        MyClass(int a) {}
        MyClass(string a) explicit {}
      }

The copy constructor is a specific constructor that the compiler can use to build more performatic code when copies of an object must be made. Without the copy constructor the compiler will be forced to first instantiate the copy using the default constructor, and then copy the attributes with the opAssign method.

A constructor that takes a single argument can be used in type conversions. By default the compiler can use these to perform the conversion implicitly when necessary. If that is not desired, then it is possible to prohibit this by adding the `explicit` decorator after the constructor.

One constructor cannot call another constructor. If you wish to share implementations in the constructors you should use a specific method for that.

If a class isn't explicitly declared with any constructor, the compiler will automatically provide a default constructor for the class. This automatically generated constructor will simply call the default constructor for all object members, and set all handles to null. If a member cannot be initialized with a default constructor, then a compiler error will be emitted.

How the members shall be initialized can also be defined directly in the declaration of the members. When this is done the initialization expression will automatically be compiled in the constructor without the need to write the initialization again.

See also
  Initialization of class members, Type conversion operators