¿Calling C++ constructor?

Monkey Forums/Monkey Programming/¿Calling C++ constructor?

JaviCervera(Posted 2011) [#1]
Monkey does not seem to know how to correctly call the correct constructor when interfacing with native C++ code. I have reproduced the bug in the following code.

I have the this native C++ class:
class TestClass {
private:
    int value;
public:
    TestClass(int value) {
        this->value = value;
    }
    
    int GetValue() {
        return this->value;
    }
};

And then, when building the following piece of Monkey code using the STDCPP target:
Strict

Import "test.cpp"

Extern
Class TestClass
Public
	Method New(value%)
	Method GetValue%()
End


Public
Function Main%()
	Local obj:TestClass = New TestClass(5)
	Print("obj value is " + obj.GetValue())
	Return 0
End

The resulting C++ code fails to compile because the line
Local obj:TestClass = New TestClass(5)

has been translated as
TestClass* bbobj=(new TestClass())->new(5);

instead of
TestClass* bbobj=new TestClass(5);

I can't find anything in the documentation explaining how to deal with native constructors, so I don't know if this has to be done in another way or what.


JaviCervera(Posted 2011) [#2]
Oops! Sorry for the wrong "¿" in the topic title. If a moderator could fix that I would be thankful.


marksibly(Posted 2011) [#3]
Hi,

Native code constructors are not supported.


JaviCervera(Posted 2011) [#4]
Thanks, Mark. So there is no way to map the "New" method to a specific "Create" function in the native class or something?


JaviCervera(Posted 2011) [#5]
Ok, this is weird.

I changed the previous test.cpp to this:
class TestClass {
private:
    int value;
public:
    TestClass(int value) {
        this->value = value;
    }
    
    int GetValue() {
        return this->value;
    }
};

TestClass* CreateTestObject(int value) {
    return new TestClass(value);
}

And the Monkey code to
Strict

Import "test.cpp"

Extern
Class TestClass
Public
	Method GetValue%()
End

Function CreateTestObject:TestClass(value%)


Public
Function Main%()
	Local obj:TestClass = CreateTestObject(5)
	Print("obj value is " + obj.GetValue())
	Return 0
End

And compilation gives the error "Missing return expression" on the CreateTestObject function, although it is in an "Extern" section, so its body is meant to be empty.


marksibly(Posted 2011) [#6]
Hi,

Working fine here, prints 'obj value is 5' with a stdcpp build.

Anyone else having problems with this?


skid(Posted 2011) [#7]
Jedive, an issue like this was fixed in MonkeyPro32, have you updated?


JaviCervera(Posted 2011) [#8]
Well, I thought that I did, but obviously not! After updating works fine. That's the problem with having several operating systems on my two computers, it's easy to forget to update your software on one of them :P

Just one more thing, is there anything in particular that I need to take care of to make the garbage collector work with native C++ classes?