question  Constructor (and Destructor?) problem

audinue (35)   Link to this post
Anyone know how to invoke constructor in the malloc/realloc-ed classes?

I have this code for reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Test
{
   int a;

public:
   Test(int a)
   {
      this->a = a;
   };

   int getA()
   {
      return a;
   };
};

#include <cstdlib>
#include <cstdio>

int main()
{
   Test *a = (Test *)malloc(sizeof(Test));

   /*
    * Calling Test's constructor ??
    */

   //printf("%d\n", a->getA()); //forbidden!
};


Thanks in advance.
satm2008 (151)   Link to this post
Not sure if malloc() works like new opeartor in C++ in terms of calling a default constructor. I guess it would call at least a base/default constructor but your code would give you a compiler error as default constructor is missing.
In C++, the new operator can be given to call a parameterized constructor for the class/object being allocated.

Just try adding a default constructor and compile it. I guess it would be OK.

Good luck :)
audinue (35)   Link to this post
Oh my...

I just wonder to make an ObjectPool (with constructors),... using malloc/realloc/free.

But I think it wouldn't be possible in C++, isn't it?

*sob*
hooked (4)   Link to this post
Maybe you can do it like this:
1
2
Test *a = (Test *)malloc(sizeof(Test));
a->Test::Test(0);


but I am not sure if it can work because I am not sure if it is in ISO
helios (4790)   Link to this post
Constructors can't be called directly.
jsmith (3099)   Link to this post
You must use new when instantiating classes. You cannot use malloc.

This topic is archived - New replies not allowed.