simple question about objects ,pointers and memory allocation

i've recently asked the same question and didn't get a good answer so ill be asking it again with some edits
why they always use
class_name *pointer = new class_name(arg)
pointer->member()

instead of
class_name object = new class_name(arg)
object.member()

im sorry im learning c++ after c# which makes this kinda confusing to me
the first we create pointer to a new object then we use it to access member/method
the second we create the object striaght then use it directly

what is the difference ? do i got it right ? which is more efficient ?
which expression in c++ create in heap and which create in stack ? and which is better or what is the use of both ?
there's no difference apart from using -> vs .

in c# any non trivial type will be allocated on the heap (and automatically free'd by the garbage collector). with c++ you can decide whether an object is created in heap or stack.

heap:
1
2
class_name *pointer = new class_name(arg)
pointer->member()

stack:
1
2
class_name obj(arg); // This is a local variable which is destroyed when the function ends
obj.member()


the second we create the object striaght then use it directly
what is this 'directly'? it's only a convention

which is more efficient ?
stack is faster
which expression in c++ create in heap and which create in stack ?
heap: lifetime of the object exceeds the current function
stack: local variable / only valid within the function
Sorry to correct in part the reply of coder777... I know I am not a programmer, but he didn't notice a thing.

The original question said:

> why they always use
> class_name *pointer = new class_name(arg)
> pointer->member()
>
> instead of
> class_name object = new class_name(arg)
> object.member()

As far as I know the second form is completely wrong. "new" operator allocates memory for a new object, and return the memory address of that object (so it returns a POINTER).
The object will survive until it will destroyed with "delete".

The correct way to create a local object (a true object to be used through value) is another one, and that one showed by coder777

1
2
class_name obj(arg); // This is a local variable which is destroyed when the function ends
obj.member()

This form is the correct way to create a "real" object to be used directly (without need to be dereferenced with ->). This object will be local, so it will be destroyed when fuction will end.

All things said by coder777 are right, however
Last edited on
Topic archived. No new replies allowed.