Hi all,
I would like to dynamically allocate space for an class instance and have its constructor called. However, it seems I am unable to get this right.
Basically, I have a class X which has other private member variables including classes Y and Z (where Y != Z). I'm getting segmentation faults and when I run my program through valgrind, it is when X is created (at the first line of main ()).
At first, I was doing this:
y_instance = new Y
which in valgrind was giving me an error about accessing data 0 bytes after 136 bytes -- so, I thought that maybe this wasn't allocating enough space for Y. I looked at:
http://www.cplusplus.com/reference/std/new/operator%20new/
and thought that when I use malloc () under C, I had to do a sizeof (). So, I tried this instead:
Y * y_instance = (Y*) operator new (sizeof(Y));
The error in X's constructor was gone, but I then got another error later on. I added a cerr inside Y's constructor, and indeed, it's not being called.
So...I'm kind of confused. How should I be doing it? Was I on the wrong track by doing "operator new"?
Prior to making Y and Z as pointers in X, they were normal variables (i.e., non-pointers). Also had a segfault and the error was less understandable. I tested Y and Z by themselves and there were no memory problems (using valgrind). So, I think it is a problem with how X is creating them, but I'm not so sure anymore...
I'd appreciate any suggestions... Thank you!
Ray