C++ and memnew()

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Karvalho
:warning: Old Version Published before Godot 3 was released.

Regarding new modules in C++, after I read this, I understood I should instantiate new classes using memnew()

When I instantiated a Dictionary, for example, like this:

Dictionary dict = memnew(Dictionary);

It worked! Great. But when I tried the same with Vector2:

Vector2 v = memnew(Vector(1, 1)); // compiler error
Vector2* v = memnew(Vector(1, 1)); // returns a boolean??? 

It didn’t work. Instead, I managed to instantiate Vector2 like this:

Vector2 v = Vector2(1, 1);

I suppose this is wrong, since it could lead to potential memory leaks? When and how should I use memnew in this case?

:bust_in_silhouette: Reply From: eaglecat

that is not wrong.
because Vector2 is not class but struct

As Zylann said classes and structs are the same in C++ other than default member visibility

nathanwfranke | 2020-02-08 02:30

:bust_in_silhouette: Reply From: Zylann

You wrote Vector, not Vector2. Vector is a different class and does not have a constructor with two integer arguments.

These should work:

Vector2 * v = memnew(Vector2(1,1));
Vector * v = memnew(Vector());

Also, struct or class doesn’t matters, they are the same in C++. The only difference is struct members are public by default.

I didn’t know that (´・ω・`)

eaglecat | 2016-04-15 07:37