Reputation: 54
For Example:
class A{
int b;
A *a1;
A *a2;
A(int c):b(c), a1(c), a2(c) {}
}
I thought this was the way, but it doesn't compile. Is there a way to do this, or is it necessary to always use dynamic allocation? thanks
Upvotes: 0
Views: 320
Reputation: 75130
If you don't want to initialise the pointers to nullptr
(NULL
or 0
pre-C++11) like this:
class A {
A(int c) : b(c), a1(), b1() { }
int b;
A* a1, *a2;
};
then either the object you make the pointer point to has to exist in some outer scope so that it will live at least as long as the object that contains the pointer, or you have to use new
.
You could accept an A*
to set the pointers to:
class A {
A(int c, A* aptr) : b(c), a1(aptr), a2(aptr) { }
...
};
(You can't use a reference for this because that would make an A
a requirement for an A
, an impossible condition to satisfy. You could make an additional constructor that accepted a reference though.)
In your example, you are trying to use an int
to initialise a pointer which won't work. Also, if you create an object in your example (via new
or whatever), you will run out of memory because each A
you allocate will allocate two more A
s and that cycle will continue until you run out of memory.
Upvotes: 1
Reputation: 182763
It's not clear what you're trying to do, but you certainly can do it:
class A{
int b;
A *a1;
A *a2;
A(int c, A* pa1, A* pa2):b(c), a1(pa1), a2(pa2) {}
}
Which you can call like this:
A m1(1, NULL, NULL);
A m2(2, NULL, NULL);
if(something())
{
A m3(3, &m1, &m2);
// do stuff with m3
}
Just be careful. If m1
or m2
go out of scope before m3
, then m3
will be left with pointers that point to random garbage.
Upvotes: 1
Reputation:
You could simply initialize the pointers to null.
class A{
int b;
A *a1;
A *a2;
A(int c):b(c), a1(NULL), a2(NULL) {}
}
(Note that if it complains about NULL not being defined, #include <cstddef
>)
Or not initialize them at all.
class A{
int b;
A *a1;
A *a2;
A(int c):b(c) {}
}
Upvotes: 1