Anyone knows how to initialize a reference in a dynamically allocated structure?
or why this doesnt work?
#include <stdio.h>
#include <stdlib.h>
class A
{
};
struct S
{
A& a;
};
int main()
{
A a;
S* s=new S;
s->a=a;
printf("a addr:%p\n", &a);
printf("s->a addr:%p\n", &(s->a));
delete s;
return 0;
}
output:
a addr:0x7fff95b65aaf
s->a addr:(nil)
You need to initialize reference members within the initializer list of a constructor. Even the body of the constructor is too late, because the member has already been initialized, and can’t be changed.
In your code, you are using the (compiler-provided) default constructor, and then trying to set the reference after the object has been constructed.
Try this: