Ok, here i have 2 simple C++ examples, the first one is:
class MyClass
{
private:
int test;
public:
int member(){
test = 456;
return 1;
} // one public function
};
int funct(MyClass** obj)
{
*obj = new MyClass();
int c = (**obj).member();
return 1;
}
...
MyClass* object;
int i = funct(&object);
...
while in the second case, i modify the main like this:
MyClass** object = (MyClass **)malloc(sizeof(MyClass));
int i = fun(object);
Both examples work fine, but i'm not sure if i understood correctly why ONLY in this second case i need a malloc (otherwise it wouldn't compile at all).
Thanks in advance for your help
PS: i know double pointers are more C-style programming, but i'm currently experimenting with both languages.
MyClass** object = (MyClass **)malloc(sizeof(MyClass));
actually this is wrong, malloc
will return pointer to allocated memory: MyClass *
, so if you later do: *object
and would like to see a pointer to MyClass
you will be wrong. You should rather:
MyClass* pobject = (MyClass *)malloc(sizeof(MyClass));
MyClass** ppobject = &pobject ;
your question is unclear to me - sorry,also it is not wise to allocate clases with malloc - your one looks like its POD - so it seems to be safe, but I would check it with std::is_pod.
[edit]
working example is below. You asked why you need initialization of object
in the second case, thats because in first case you reserve storage for your pointer by simply defining pointer variable : MyClass* object;
. Here object
can be safely used in funct
. In second example, you dont have reserved memory (in this case space on stack) for your pointer to MyClass, so you must allocate it with malloc or new. Hopefully thats clear enough.
MyClass** object = (MyClass **)malloc(sizeof(MyClass*));
//MyClass** object = new MyClass*;
int i = funct(object);
delete *object;
free(object);
//delete object;