Hi, I'm looking for a way to use a composite object with Nim.
Please how do you write this cpp example, with Nim ? Sorry for the lack of sense of this code. I looked for the shortest example, just to make things work.
#include <iostream>
class A
{
public:
int member;
A(int arg);
};
A::A(int arg = 1)
{
member = arg;
}
class B
{
public:
int member;
B(int arg);
};
B::B(int arg = 2)
{
member = arg;
}
class Ab
{
public:
A a;
B b;
int sum();
};
int Ab::sum()
{
return a.member + b.member;
}
int main(int argc, char **argv)
{
Ab ab;
std::cout << ab.sum() << std::endl;
return 0;
}
Thanks in advance.
Nim has no default constructors for object fields, so you have to initialize them explicitly. Other than that, here you go:
type
A* = object
member*: int
B* = object
member*: int
Ab* = object
a*: A
b*: B
proc initA(arg: int = 1): A =
A(member: arg)
proc initB(arg: int = 2): B =
B(member: arg)
proc initAb: Ab =
Ab(a: initA(), b: initB())
proc add(ab: Ab): int =
ab.a.member + ab.b.member
proc main =
let ab = initAb()
echo ab.add()
main()
Note that constructors in Nim are normal procedures that simply return an object of that type.
proc add(ab: Ab): int =
ab.a.member + ab.b.member
Sorry for the little edit on my thread post before checking for an answer post.