Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor in Ada

Tags:

java

ada

I am trying to implement a constructor like it is used in Java or C++ in Ada 2005.

I have this class in Java:

public class MyClass {
    private static int intTest = 0; 
    private float floatTest = 0.0f; 
    private float floatTest2 = 0.0f; 

    public MyClass(float f_test, float f_test1) {
        MyClass.intTest++;
        this.floatTest = f_test;
        this.floatTest2 = f_test1;       
    }
}

And now I am trying to implement this in Ada 2005. This is what I did but I get an error.

with Ada.Finalization; use Ada.Finalization;
package MyClasses is    
    type MyClass (f_test, f_test1 : float)
        is new Controlled with private; 
    type MyClass is access all MyClass'Class;   
    private
        intTest : Integer := 0;
        type MyClass( f_test, f_test1: float )
            is new Controlled with
            record
                floatTest : float := f_test;
                floatTest2 : float := f_test1;
            end record;
overriding procedure Initialize (This : in out MyClass);    
end MyClass;

with Ada.Text_IO; 
use Ada.Text_IO;
package body MyClasses is
    procedure Initialize( This : in out MyClass ) is
    begin       
        intTest := intTest + 1;     
    end Initialize;
end MyClass;

On this line I get the error "discriminants must have a discrete or access type".

type MyClass (f_test, f_test1 : float)
    is new Controlled with private;

How can I implement the constructor like it is in the java class?

like image 307
user1058712 Avatar asked May 13 '26 03:05

user1058712


1 Answers

Float is not a discrete type and "discriminants must have a discrete or access type". Ada does not have the kind of constructors you find in the C++ inspired family of languages. Trying to repurpose discriminants for that is like trying to hammer a screw into the wall. If it does happen to work the result still won't be pretty.

Rather you should have a creator function that returns your initialized object:

type MyClass is new Controlled with private;
function Create(f_test, f_test1 : float) return MyClass;

Other things to note:

  • Your access type MyClass has the same name as the record type. That won't work.
  • You declared intTest as private static in the Java example, but declared it in the private part of the Ada package. This is equivalent to protected since child packages can access it. Declare it in the package body instead, this is the true equivalent of private static.
like image 180
Andreas Bombe Avatar answered May 15 '26 17:05

Andreas Bombe